diff --git a/packages/twenty-shared/src/utils/validation/phones-value/getCountryCodesForCallingCode.ts b/packages/twenty-shared/src/utils/validation/phones-value/getCountryCodesForCallingCode.ts index be7a21487e4e7..de2fc1f085e05 100644 --- a/packages/twenty-shared/src/utils/validation/phones-value/getCountryCodesForCallingCode.ts +++ b/packages/twenty-shared/src/utils/validation/phones-value/getCountryCodesForCallingCode.ts @@ -1,15 +1,30 @@ -import { getCountries, getCountryCallingCode } from 'libphonenumber-js'; +import { + type CountryCode, + getCountries, + getCountryCallingCode, +} from 'libphonenumber-js'; -const ALL_COUNTRIES_CODE = getCountries(); +// Precompute a map from calling code to country codes for O(1) lookups +const CALLING_CODE_TO_COUNTRIES = new Map(); -export const getCountryCodesForCallingCode = (callingCode: string) => { +for (const country of getCountries()) { + const callingCode = getCountryCallingCode(country); + + const existing = CALLING_CODE_TO_COUNTRIES.get(callingCode); + + if (existing) { + existing.push(country); + } else { + CALLING_CODE_TO_COUNTRIES.set(callingCode, [country]); + } +} + +export const getCountryCodesForCallingCode = ( + callingCode: string, +): CountryCode[] => { const cleanCallingCode = callingCode.startsWith('+') ? callingCode.slice(1) : callingCode; - return ALL_COUNTRIES_CODE.filter((country) => { - const countryCallingCode = getCountryCallingCode(country); - - return countryCallingCode === cleanCallingCode; - }); + return CALLING_CODE_TO_COUNTRIES.get(cleanCallingCode) ?? []; }; diff --git a/packages/twenty-shared/src/utils/validation/phones-value/isValidCountryCode.ts b/packages/twenty-shared/src/utils/validation/phones-value/isValidCountryCode.ts index 6df428e2a7484..ff48a7c0d4e97 100644 --- a/packages/twenty-shared/src/utils/validation/phones-value/isValidCountryCode.ts +++ b/packages/twenty-shared/src/utils/validation/phones-value/isValidCountryCode.ts @@ -1,7 +1,7 @@ import { type CountryCode, getCountries } from 'libphonenumber-js'; -const ALL_COUNTRIES_CODE = getCountries(); +const ALL_COUNTRIES_CODE_SET = new Set(getCountries()); export const isValidCountryCode = (input: string): input is CountryCode => { - return ALL_COUNTRIES_CODE.includes(input as unknown as CountryCode); + return ALL_COUNTRIES_CODE_SET.has(input); };