From 5ebe32adcb74a2c77b89b158dd0953961bc09e1a Mon Sep 17 00:00:00 2001 From: Dmytro Date: Mon, 4 Mar 2024 17:45:45 +0200 Subject: [PATCH] Case insensitive search in getCountryCode function #131 --- packages/countries/src/getCountryCode.ts | 12 +++++++++--- packages/test-node/getCountryCode.test.ts | 6 ++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/countries/src/getCountryCode.ts b/packages/countries/src/getCountryCode.ts index e106c76..c3439b6 100644 --- a/packages/countries/src/getCountryCode.ts +++ b/packages/countries/src/getCountryCode.ts @@ -3,6 +3,12 @@ import { getCountryDataList } from './getCountryData.ts' const countryDataList = getCountryDataList() -export const getCountryCode = (countryName: string): TCountryCode | false => - countryDataList.find(({ name, native }) => countryName === name || countryName === native) - ?.iso2 || false +export const getCountryCode = (countryName: string): TCountryCode | false => { + // Match exact country name, but case insensitive + const nameRegex = new RegExp('^' + countryName + '$', 'i') + + return ( + countryDataList.find(({ name, native }) => nameRegex.test(name) || nameRegex.test(native)) + ?.iso2 || false + ) +} diff --git a/packages/test-node/getCountryCode.test.ts b/packages/test-node/getCountryCode.test.ts index 6e323fb..08ee17f 100644 --- a/packages/test-node/getCountryCode.test.ts +++ b/packages/test-node/getCountryCode.test.ts @@ -5,5 +5,11 @@ import { getCountryCode } from 'src/getCountryCode.ts' test('getCountryCode()', () => { assert.equal(getCountryCode('Ukraine'), 'UA') + assert.equal(getCountryCode('uKraine'), 'UA') assert.equal(getCountryCode('Україна'), 'UA') + assert.equal(getCountryCode('уКраїна'), 'UA') + + assert.equal(getCountryCode('Ukrain'), false) + assert.equal(getCountryCode('Ukraine1'), false) + assert.equal(getCountryCode('Unknown'), false) })