getCountryByNationalNumber.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import Metadata from '../metadata.js'
  2. import getNumberType from './getNumberType.js'
  3. export default function getCountryByNationalNumber(nationalPhoneNumber, {
  4. countries,
  5. defaultCountry,
  6. metadata
  7. }) {
  8. // Re-create `metadata` because it will be selecting a `country`.
  9. metadata = new Metadata(metadata)
  10. const matchingCountries = []
  11. for (const country of countries) {
  12. metadata.country(country)
  13. // "Leading digits" patterns are only defined for about 20% of all countries.
  14. // By definition, matching "leading digits" is a sufficient but not a necessary
  15. // condition for a phone number to belong to a country.
  16. // The point of "leading digits" check is that it's the fastest one to get a match.
  17. // https://gitlab.com/catamphetamine/libphonenumber-js/blob/master/METADATA.md#leading_digits
  18. // I'd suppose that "leading digits" patterns are mutually exclusive for different countries
  19. // because of the intended use of that feature.
  20. if (metadata.leadingDigits()) {
  21. if (nationalPhoneNumber &&
  22. nationalPhoneNumber.search(metadata.leadingDigits()) === 0) {
  23. return country
  24. }
  25. }
  26. // Else perform full validation with all of those
  27. // fixed-line/mobile/etc regular expressions.
  28. else if (getNumberType({ phone: nationalPhoneNumber, country }, undefined, metadata.metadata)) {
  29. // If the `defaultCountry` is among the `matchingCountries` then return it.
  30. if (defaultCountry) {
  31. if (country === defaultCountry) {
  32. return country
  33. }
  34. matchingCountries.push(country)
  35. } else {
  36. return country
  37. }
  38. }
  39. }
  40. // Return the first ("main") one of the `matchingCountries`.
  41. if (matchingCountries.length > 0) {
  42. return matchingCountries[0]
  43. }
  44. }