@@ -130,8 +130,8 @@ const DISTRICT_SPLIT_REGEX = /^([a-z]{1,2}\d)([a-z])$/i;
130130 * @example
131131 *
132132 * ```
133- * toDistrict("AA9") // => "AA9"
134- * toDistrict("A9A") // => "A9"
133+ * toDistrict("AA9 9AA ") // => "AA9"
134+ * toDistrict("A9A 9AA ") // => "A9"
135135 * ```
136136 */
137137const toDistrict : Parser = postcode => {
@@ -142,6 +142,29 @@ const toDistrict: Parser = postcode => {
142142 return match [ 1 ] ;
143143} ;
144144
145+ /**
146+ * Returns a correctly formatted subdistrict given a postcode
147+ *
148+ * Returns null if no subdistrict is available on valid postcode
149+ * Returns null if invalid postcode
150+ *
151+ * @example
152+ *
153+ * ```
154+ * toSubDistrict("AA9A 9AA") // => "AA9A"
155+ * toSubDistrict("A9A 9AA") // => "A9A"
156+ * toSubDistrict("AA9 9AA") // => null
157+ * toSubDistrict("A9 9AA") // => null
158+ * ```
159+ */
160+ const toSubDistrict : Parser = postcode => {
161+ const outcode = toOutcode ( postcode ) ;
162+ if ( outcode === null ) return null ;
163+ const split = outcode . match ( DISTRICT_SPLIT_REGEX ) ;
164+ if ( split === null ) return null ;
165+ return outcode ;
166+ } ;
167+
145168const returnNull = ( ) => null ;
146169
147170/**
@@ -190,6 +213,7 @@ class Postcode {
190213 static toSector = toSector ;
191214 static toUnit = toUnit ;
192215 static toDistrict = toDistrict ;
216+ static toSubDistrict = toSubDistrict ;
193217
194218 static validOutcode ( outcode : string ) : boolean {
195219 return outcode . match ( validOutcodeRegex ) !== null ;
@@ -223,12 +247,8 @@ class Postcode {
223247 }
224248
225249 subDistrict ( ) : string | null {
226- if ( ! this . _valid ) return null ;
227250 if ( this . _subDistrict ) return this . _subDistrict ;
228- const outcode = this . outcode ( ) ;
229- if ( outcode === null ) return null ;
230- const split = outcode . match ( DISTRICT_SPLIT_REGEX ) ;
231- this . _subDistrict = split !== null ? outcode : null ;
251+ this . _subDistrict = toSubDistrict ( this . _raw ) ;
232252 return this . _subDistrict ;
233253 }
234254
0 commit comments