UNPKG

2.3 kBJavaScriptView Raw
1import _formatNumber from './format_'
2import parse from './parse_'
3
4export default function formatNumber()
5{
6 const
7 {
8 input,
9 format,
10 options,
11 metadata
12 }
13 = normalizeArguments(arguments)
14
15 return _formatNumber(input, format, options, metadata)
16}
17
18// Sort out arguments
19function normalizeArguments(args)
20{
21 const [arg_1, arg_2, arg_3, arg_4, arg_5] = Array.prototype.slice.call(args)
22
23 let input
24 let format
25 let options
26 let metadata
27
28 // Sort out arguments.
29
30 // If the phone number is passed as a string.
31 // `format('8005553535', ...)`.
32 if (typeof arg_1 === 'string')
33 {
34 // If country code is supplied.
35 // `format('8005553535', 'RU', 'NATIONAL', [options], metadata)`.
36 if (typeof arg_3 === 'string')
37 {
38 format = arg_3
39
40 if (arg_5)
41 {
42 options = arg_4
43 metadata = arg_5
44 }
45 else
46 {
47 metadata = arg_4
48 }
49
50 input = parse(arg_1, { defaultCountry: arg_2, extended: true }, metadata)
51 }
52 // Just an international phone number is supplied
53 // `format('+78005553535', 'NATIONAL', [options], metadata)`.
54 else
55 {
56 if (typeof arg_2 !== 'string')
57 {
58 throw new Error('`format` argument not passed to `formatNumber(number, format)`')
59 }
60
61 format = arg_2
62
63 if (arg_4)
64 {
65 options = arg_3
66 metadata = arg_4
67 }
68 else
69 {
70 metadata = arg_3
71 }
72
73 input = parse(arg_1, { extended: true }, metadata)
74 }
75 }
76 // If the phone number is passed as a parsed number object.
77 // `format({ phone: '8005553535', country: 'RU' }, 'NATIONAL', [options], metadata)`.
78 else if (is_object(arg_1))
79 {
80 input = arg_1
81 format = arg_2
82
83 if (arg_4)
84 {
85 options = arg_3
86 metadata = arg_4
87 }
88 else
89 {
90 metadata = arg_3
91 }
92 }
93 else throw new TypeError('A phone number must either be a string or an object of shape { phone, [country] }.')
94
95 // Legacy lowercase formats.
96 if (format === 'International') {
97 format = 'INTERNATIONAL'
98 } else if (format === 'National') {
99 format = 'NATIONAL'
100 }
101
102 return {
103 input,
104 format,
105 options,
106 metadata
107 }
108}
109
110// Babel transforms `typeof` into some "branches"
111// so istanbul will show this as "branch not covered".
112/* istanbul ignore next */
113const is_object = _ => typeof _ === 'object'
\No newline at end of file