|
| 1 | +/** |
| 2 | + * @hidden |
| 3 | + */ |
1 | 4 | export const DISTRICT_SPLIT_REGEX = /^([a-z]{1,2}\d)([a-z])$/i; |
| 5 | +/** |
| 6 | + * Tests for the unit section of a postcode |
| 7 | + */ |
2 | 8 | export const UNIT_REGEX = /[a-z]{2}$/i; |
| 9 | +/** |
| 10 | + * Tests for the inward code section of a postcode |
| 11 | + */ |
3 | 12 | export const INCODE_REGEX = /\d[a-z]{2}$/i; |
| 13 | +/** |
| 14 | + * Tests for the outward code section of a postcode |
| 15 | + */ |
4 | 16 | export const OUTCODE_REGEX = /^[a-z]{1,2}\d[a-z\d]?$/i; |
| 17 | +/** |
| 18 | + * Tests for a valid postcode |
| 19 | + */ |
5 | 20 | export const POSTCODE_REGEX = /^[a-z]{1,2}\d[a-z\d]?\s*\d[a-z]{2}$/i; |
| 21 | + |
| 22 | +/** |
| 23 | + * Tests for the area section of a postcode |
| 24 | + */ |
6 | 25 | export const AREA_REGEX = /^[a-z]{1,2}/i; |
7 | 26 |
|
| 27 | +/** |
| 28 | + * @hidden |
| 29 | + */ |
8 | 30 | interface Validator { |
9 | 31 | (input: string): boolean; |
10 | 32 | } |
11 | 33 |
|
12 | 34 | interface Parser { |
| 35 | + /** |
| 36 | + * @hidden |
| 37 | + */ |
13 | 38 | (postcode: string): string | null; |
14 | 39 | } |
15 | 40 |
|
@@ -37,6 +62,10 @@ type InvalidPostcode = { |
37 | 62 | unit: null; |
38 | 63 | }; |
39 | 64 |
|
| 65 | +/** |
| 66 | + * Invalid postcode prototype |
| 67 | + * @hidden |
| 68 | + */ |
40 | 69 | const invalidPostcode: InvalidPostcode = { |
41 | 70 | valid: false, |
42 | 71 | postcode: null, |
@@ -209,6 +238,36 @@ export const toSubDistrict: Parser = (postcode) => { |
209 | 238 |
|
210 | 239 | /** |
211 | 240 | * Returns a ValidPostcode or InvalidPostcode object from a postcode string |
| 241 | + * |
| 242 | + * @example |
| 243 | + * |
| 244 | + * ``` |
| 245 | + * import { parse } from "postcode"; |
| 246 | + * |
| 247 | + * const { |
| 248 | + * postcode, // => "SW1A 2AA" |
| 249 | + * outcode, // => "SW1A" |
| 250 | + * incode, // => "2AA" |
| 251 | + * area, // => "SW" |
| 252 | + * district, // => "SW1" |
| 253 | + * unit, // => "AA" |
| 254 | + * sector, // => "SW1A 2" |
| 255 | + * subDistrict, // => "SW1A" |
| 256 | + * valid, // => true |
| 257 | + * } = parse("Sw1A 2aa"); |
| 258 | + * |
| 259 | + * const { |
| 260 | + * postcode, // => null |
| 261 | + * outcode, // => null |
| 262 | + * incode, // => null |
| 263 | + * area, // => null |
| 264 | + * district, // => null |
| 265 | + * unit, // => null |
| 266 | + * sector, // => null |
| 267 | + * subDistrict, // => null |
| 268 | + * valid, // => false |
| 269 | + * } = parse(" Oh no, ): "); |
| 270 | + * ``` |
212 | 271 | */ |
213 | 272 | export const parse = (postcode: string): ValidPostcode | InvalidPostcode => { |
214 | 273 | if (!isValid(postcode)) return { ...invalidPostcode }; |
|
0 commit comments