From 4442dc9355c58811bd69ec1484fd4b6a01aae25a Mon Sep 17 00:00:00 2001 From: Damian Mee Date: Thu, 29 Aug 2024 19:24:56 +0200 Subject: [PATCH] Add name normalisation, as I can't imagine when "Virgin Islands, British" returned would be preferred over "British Virgin Islands". Inspired by and closes #19 --- src/lib.js | 23 ++++++++++++++++------- test/name.js | 5 +++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/lib.js b/src/lib.js index 1a32131..9480d31 100644 --- a/src/lib.js +++ b/src/lib.js @@ -6,6 +6,16 @@ export const CODE_RE = /^[a-z]{2}$/i; export const NAME_RE = /^.{2,}$/; export const FLAG_RE = /\uD83C[\uDDE6-\uDDFF]/; +const NAME_SEP = ', '; + +function normalizeName(name) { + if (!name || !name.includes(NAME_SEP)) { + return name; + } + + return name.split(NAME_SEP).reverse().join(' '); +} + export function fuzzyCompare(input, name) { name = name.toLowerCase(); @@ -16,12 +26,13 @@ export function fuzzyCompare(input, name) { return true; } + const normalizedName = normalizeName(name); + // Cases like: // "British Virgin Islands" <-> "Virgin Islands, British" // "Republic of Moldova" <-> "Moldova, Republic of" - if (name.includes(',')) { - const reversedName = name.split(', ').reverse().join(' '); - if (reversedName.includes(input) || input.includes(reversedName)) { + if (normalizedName !== name) { + if (normalizedName.includes(input) || input.includes(normalizedName)) { return true; } } @@ -67,7 +78,7 @@ export function codeToName(code) { return; } - return countries[code.toUpperCase()]?.[0]; + return normalizeName(countries[code.toUpperCase()]?.[0]); } export function codeToFlag(code) { @@ -80,9 +91,7 @@ export function codeToFlag(code) { return; } - if (String && String.fromCodePoint) { - return String.fromCodePoint(...[...code].map(c => MAGIC_NUMBER + c.codePointAt(0))); - } + return String.fromCodePoint(...[...code].map(c => MAGIC_NUMBER + c.codePointAt(0))); } export function flagToCode(flag) { diff --git a/test/name.js b/test/name.js index caca987..02eaebb 100644 --- a/test/name.js +++ b/test/name.js @@ -42,6 +42,11 @@ test('returns first name from array for code US', t => { t.is(country, 'United States', 'Should return United States for code US'); }); +test('returns normalized name', t => { + const country = name('VG'); + t.is(country, 'British Virgin Islands', 'Should return British Virgin Islands for code VG'); +}); + test('returns correct name for Macedonian country code', t => { const country = name('MK'); t.is(country, 'Republic of North Macedonia', 'Should return correct name for code MK');