import countryData from 'country-data' ; import esData from './data/countries/es/country.json' ; import { getExampleNumber } from './phoneNumbers' ; interface CountryNames { [ name ] : string ; } deprecated celo export interface LocalizedCountry extends Omit < countryData . Country , 'countryCallingCodes' > { displayName : string ; displayNameNoDiacritics : string ; names : CountryNames ; countryPhonePlaceholder : { national ? : string | undefined ; international ? : string | undefined ; } ; countryCallingCode : string ; } const removeDiacritics = ( word ) => word && word . normalize ( 'NFD' ) . replace ( /[\u0300-\u036f]/g , '' ) . toLowerCase ( ) . trim ( ) ; const matchCountry = ( country , query ) => { return ( country . displayNameNoDiacritics . startsWith ( query ) || country . countryCallingCode . startsWith ( '+' + query ) || country . alpha3 . startsWith ( query . toUpperCase ( ) ) ) ; } ; deprecated celo export class Countries { language : string ; countryMap : Map < string , LocalizedCountry > ; localizedCountries : LocalizedCountry [ ] ; constructor ( language ? ) { this . language = language ? language . toLocaleLowerCase ( ) : 'en-us' ; this . countryMap = new Map ( ) ; this . localizedCountries = Array ( ) ; this . assignCountries ( ) ; } getCountry ( countryName ? ) { if ( ! countryName ) { return undefined ; } const query = removeDiacritics ( countryName ) ; return this . localizedCountries . find ( ( country ) => country . displayNameNoDiacritics === query ) ; } getCountryByCodeAlpha2 ( countryCode ) { return this . countryMap . get ( countryCode ) ; } getFilteredCountries ( query ) { query = removeDiacritics ( query ) ; if ( ! query || ! query . length ) { return this . localizedCountries ; } return this . localizedCountries . filter ( ( country ) => matchCountry ( country , query ) ) ; } private assignCountries ( ) { this . localizedCountries = countryData . callingCountries . all . map ( ( country ) => { const names = { 'en-us' : country . name , 'es-419' : esData [ country . alpha2 ] } ; const displayName = names [ this . language ] || country . name ; const countryCallingCode = country . countryCallingCodes [ 0 ] . split ( ' ' ) [ 0 ] ; const localizedCountry = { names , displayName , displayNameNoDiacritics : removeDiacritics ( displayName ) , countryPhonePlaceholder : { national : getExampleNumber ( countryCallingCode ) } , countryCallingCode , ... country , emoji : country . emoji || '🏳' } ; this . countryMap . set ( country . alpha2 . toUpperCase ( ) , localizedCountry ) ; return localizedCountry ; } ) . sort ( ( a , b ) => a . displayName . localeCompare ( b . displayName ) ) ; } }