normalizeArguments.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import isObject from './helpers/isObject.js'
  2. // Extracts the following properties from function arguments:
  3. // * input `text`
  4. // * `options` object
  5. // * `metadata` JSON
  6. export default function normalizeArguments(args) {
  7. const [arg_1, arg_2, arg_3, arg_4] = Array.prototype.slice.call(args)
  8. let text
  9. let options
  10. let metadata
  11. // If the phone number is passed as a string.
  12. // `parsePhoneNumber('88005553535', ...)`.
  13. if (typeof arg_1 === 'string') {
  14. text = arg_1
  15. }
  16. else throw new TypeError('A text for parsing must be a string.')
  17. // If "default country" argument is being passed then move it to `options`.
  18. // `parsePhoneNumber('88005553535', 'RU', [options], metadata)`.
  19. if (!arg_2 || typeof arg_2 === 'string')
  20. {
  21. if (arg_4) {
  22. options = arg_3
  23. metadata = arg_4
  24. } else {
  25. options = undefined
  26. metadata = arg_3
  27. }
  28. if (arg_2) {
  29. options = { defaultCountry: arg_2, ...options }
  30. }
  31. }
  32. // `defaultCountry` is not passed.
  33. // Example: `parsePhoneNumber('+78005553535', [options], metadata)`.
  34. else if (isObject(arg_2))
  35. {
  36. if (arg_3) {
  37. options = arg_2
  38. metadata = arg_3
  39. } else {
  40. metadata = arg_2
  41. }
  42. }
  43. else throw new Error(`Invalid second argument: ${arg_2}`)
  44. return {
  45. text,
  46. options,
  47. metadata
  48. }
  49. }