@@ -29,7 +29,6 @@ const matchOn = (s: string, regex: RegExp): RegExpMatchArray | null => {
2929
3030const incodeRegex = / \d [ a - z ] { 2 } $ / i;
3131const validOutcodeRegex = / ^ [ a - z ] { 1 , 2 } \d [ a - z \d ] ? $ / i;
32- const districtSplitRegex = / ^ ( [ a - z ] { 1 , 2 } \d ) ( [ a - z ] ) $ / i;
3332const VALIDATION_REGEX = / ^ [ a - z ] { 1 , 2 } \d [ a - z \d ] ? \s * \d [ a - z ] { 2 } $ / i;
3433
3534/**
@@ -121,6 +120,28 @@ const toUnit: Parser = postcode => {
121120 return firstOrNull ( match ) ;
122121} ;
123122
123+ const DISTRICT_SPLIT_REGEX = / ^ ( [ a - z ] { 1 , 2 } \d ) ( [ a - z ] ) $ / i;
124+
125+ /**
126+ * Returns a correctly formatted district given a postcode
127+ *
128+ * Returns null if invalid postcode
129+ *
130+ * @example
131+ *
132+ * ```
133+ * toDistrict("AA9") // => "AA9"
134+ * toDistrict("A9A") // => "A9"
135+ * ```
136+ */
137+ const toDistrict : Parser = postcode => {
138+ const outcode = toOutcode ( postcode ) ;
139+ if ( outcode === null ) return null ;
140+ const match = outcode . match ( DISTRICT_SPLIT_REGEX ) ;
141+ if ( match === null ) return outcode ;
142+ return match [ 1 ] ;
143+ } ;
144+
124145const returnNull = ( ) => null ;
125146
126147/**
@@ -168,6 +189,7 @@ class Postcode {
168189 static toArea = toArea ;
169190 static toSector = toSector ;
170191 static toUnit = toUnit ;
192+ static toDistrict = toDistrict ;
171193
172194 static validOutcode ( outcode : string ) : boolean {
173195 return outcode . match ( validOutcodeRegex ) !== null ;
@@ -196,21 +218,16 @@ class Postcode {
196218 }
197219
198220 district ( ) : string | null {
199- if ( ! this . _valid ) return null ;
200221 if ( this . _district ) return this . _district ;
201- const outcode = this . outcode ( ) ;
202- if ( outcode === null ) return null ;
203- const split = outcode . match ( districtSplitRegex ) ;
204- this . _district = split !== null ? split [ 1 ] : outcode ;
205- return this . _district ;
222+ return ( this . _district = toDistrict ( this . _raw ) ) ;
206223 }
207224
208225 subDistrict ( ) : string | null {
209226 if ( ! this . _valid ) return null ;
210227 if ( this . _subDistrict ) return this . _subDistrict ;
211228 const outcode = this . outcode ( ) ;
212229 if ( outcode === null ) return null ;
213- const split = outcode . match ( districtSplitRegex ) ;
230+ const split = outcode . match ( DISTRICT_SPLIT_REGEX ) ;
214231 this . _subDistrict = split !== null ? outcode : null ;
215232 return this . _subDistrict ;
216233 }
0 commit comments