Skip to content

Commit 95f1d0e

Browse files
committed
feat(Match): Implement match
Returns a list of valid postcodes within a body of text
1 parent dd1315d commit 95f1d0e

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

lib/index.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ export const OUTCODE_REGEX = /^[a-z]{1,2}\d[a-z\d]?$/i;
1919
*/
2020
export const POSTCODE_REGEX = /^[a-z]{1,2}\d[a-z\d]?\s*\d[a-z]{2}$/i;
2121

22+
/**
23+
* Test for a valid postcode embedded in text
24+
*/
25+
export const POSTCODE_CORPUS_REGEX = /[a-z]{1,2}\d[a-z\d]?\s*\d[a-z]{2}/gi;
26+
2227
/**
2328
* Tests for the area section of a postcode
2429
*/
@@ -283,3 +288,11 @@ export const parse = (postcode: string): ValidPostcode | InvalidPostcode => {
283288
unit: toUnit(postcode) as string,
284289
};
285290
};
291+
292+
/**
293+
* Searches a body of text for postcode matches
294+
*
295+
* Returns an empty array if no match
296+
*/
297+
export const match = (corpus: string): string[] =>
298+
corpus.match(POSTCODE_CORPUS_REGEX) || [];

test/unit.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { assert } from "chai";
22
import * as Postcode from "../lib/index";
33
import { loadFixtures, TestMethod } from "./util/helper";
44

5+
const { match } = Postcode;
6+
57
const testMethod: TestMethod = (options) => {
68
const { tests, method } = options;
79
tests.forEach(({ base, expected }) => {
@@ -123,3 +125,15 @@ describe("Unit parsing", () => {
123125
assert.isNull(Postcode.parse("Definitely bogus").unit);
124126
});
125127
});
128+
129+
describe("match", () => {
130+
it("returns matching postcodes", () => {
131+
const corpus = `SW1A2Aa is the residence of the Prime Minister. SW1a 2AB is the residence of her no.2. SW1A 1AA is where the queen lives. They are located in the SW1A outcode`;
132+
assert.deepEqual(match(corpus), ["SW1A2Aa", "SW1a 2AB", "SW1A 1AA"]);
133+
});
134+
135+
it("returns an empty array if no match", () => {
136+
const corpus = `SW1 NW1 E1 E2`;
137+
assert.deepEqual(match(corpus), []);
138+
});
139+
});

0 commit comments

Comments
 (0)