Skip to content

The open alternative to Salesforce, designed for AI.

Fix phone validation performance by using Set/Map instead of Array lookups (#17843)

Félix Malfait9c984b137f41
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 be7a21487e4..de2fc1f085e 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<string, CountryCode[]>();
-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 6df428e2a74..ff48a7c0d4e 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<string>(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);
};