Clean up phone number formatting (#1015)

This commit is contained in:
Fahim Faisaal
2022-05-16 22:48:16 +06:00
committed by GitHub
parent f736217341
commit c865654f27
2 changed files with 21 additions and 30 deletions

View File

@ -1,17 +1,16 @@
// function that takes 10 digits and returns a string of the formatted phone number
// e.g.: 1234567890 -> (123) 456-7890
const formatPhoneNumber = (numbers) => {
const numbersString = numbers.toString()
if ((numbersString.length !== 10) || isNaN(numbersString)) {
/**
* @description - function that takes 10 digits and returns a string of the formatted phone number e.g.: 1234567890 -> (123) 456-7890
* @param {string} phoneNumber
* @returns {string} - Format to (XXX) XXX-XXXX pattern
*/
const formatPhoneNumber = (phoneNumber) => {
if ((phoneNumber.length !== 10) || isNaN(phoneNumber)) {
// return "Invalid phone number."
throw new TypeError('Invalid phone number.')
throw new TypeError('Invalid phone number!')
}
const arr = '(XXX) XXX-XXXX'.split('')
Array.from(numbersString).forEach(n => {
arr[arr.indexOf('X')] = n
})
return arr.join('')
let index = 0
return '(XXX) XXX-XXXX'.replace(/X/g, () => phoneNumber[index++])
}
export { formatPhoneNumber }
export default formatPhoneNumber