File size: 783 Bytes
d9494a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import {
  type CountryCode,
  getCountries,
  getCountryCallingCode,
} from 'libphonenumber-js';

// Precompute a map from calling code to country codes for O(1) lookups
const CALLING_CODE_TO_COUNTRIES = new Map<string, CountryCode[]>();

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 CALLING_CODE_TO_COUNTRIES.get(cleanCallingCode) ?? [];
};