format.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import _formatNumber from '../format.js'
  2. import parse from '../parse.js'
  3. import isObject from '../helpers/isObject.js'
  4. export default function formatNumber() {
  5. const {
  6. input,
  7. format,
  8. options,
  9. metadata
  10. } = normalizeArguments(arguments)
  11. return _formatNumber(input, format, options, metadata)
  12. }
  13. // Sort out arguments
  14. function normalizeArguments(args)
  15. {
  16. const [arg_1, arg_2, arg_3, arg_4, arg_5] = Array.prototype.slice.call(args)
  17. let input
  18. let format
  19. let options
  20. let metadata
  21. // Sort out arguments.
  22. // If the phone number is passed as a string.
  23. // `format('8005553535', ...)`.
  24. if (typeof arg_1 === 'string')
  25. {
  26. // If country code is supplied.
  27. // `format('8005553535', 'RU', 'NATIONAL', [options], metadata)`.
  28. if (typeof arg_3 === 'string')
  29. {
  30. format = arg_3
  31. if (arg_5)
  32. {
  33. options = arg_4
  34. metadata = arg_5
  35. }
  36. else
  37. {
  38. metadata = arg_4
  39. }
  40. input = parse(arg_1, { defaultCountry: arg_2, extended: true }, metadata)
  41. }
  42. // Just an international phone number is supplied
  43. // `format('+78005553535', 'NATIONAL', [options], metadata)`.
  44. else
  45. {
  46. if (typeof arg_2 !== 'string')
  47. {
  48. throw new Error('`format` argument not passed to `formatNumber(number, format)`')
  49. }
  50. format = arg_2
  51. if (arg_4)
  52. {
  53. options = arg_3
  54. metadata = arg_4
  55. }
  56. else
  57. {
  58. metadata = arg_3
  59. }
  60. input = parse(arg_1, { extended: true }, metadata)
  61. }
  62. }
  63. // If the phone number is passed as a parsed number object.
  64. // `format({ phone: '8005553535', country: 'RU' }, 'NATIONAL', [options], metadata)`.
  65. else if (isObject(arg_1))
  66. {
  67. input = arg_1
  68. format = arg_2
  69. if (arg_4)
  70. {
  71. options = arg_3
  72. metadata = arg_4
  73. }
  74. else
  75. {
  76. metadata = arg_3
  77. }
  78. }
  79. else throw new TypeError('A phone number must either be a string or an object of shape { phone, [country] }.')
  80. // Legacy lowercase formats.
  81. if (format === 'International') {
  82. format = 'INTERNATIONAL'
  83. } else if (format === 'National') {
  84. format = 'NATIONAL'
  85. }
  86. return {
  87. input,
  88. format,
  89. options,
  90. metadata
  91. }
  92. }