Skip to content

Commit

Permalink
Case insensitive search in getCountryCode function #131
Browse files Browse the repository at this point in the history
  • Loading branch information
dmythro committed Mar 4, 2024
1 parent 9a0e968 commit 5ebe32a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
12 changes: 9 additions & 3 deletions packages/countries/src/getCountryCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
}
6 changes: 6 additions & 0 deletions packages/test-node/getCountryCode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})

0 comments on commit 5ebe32a

Please sign in to comment.