mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
Add Phone Number Formatting Function
This commit is contained in:
17
String/FormatPhoneNumber.js
Normal file
17
String/FormatPhoneNumber.js
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// 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)) {
|
||||||
|
// return "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('')
|
||||||
|
}
|
||||||
|
|
||||||
|
export { formatPhoneNumber }
|
23
String/FormatPhoneNumber.test.js
Normal file
23
String/FormatPhoneNumber.test.js
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
import { formatPhoneNumber } from './FormatPhoneNumber'
|
||||||
|
|
||||||
|
describe('PhoneNumberFormatting', () => {
|
||||||
|
it('expects to return the formatted phone number', () => {
|
||||||
|
expect(formatPhoneNumber('1234567890')).toEqual('(123) 456-7890')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('expects to return the formatted phone number', () => {
|
||||||
|
expect(formatPhoneNumber(1234567890)).toEqual('(123) 456-7890')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('expects to throw a type error', () => {
|
||||||
|
expect(() => { formatPhoneNumber('1234567') }).toThrow('Invalid phone number.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('expects to throw a type error', () => {
|
||||||
|
expect(() => { formatPhoneNumber('123456text') }).toThrow('Invalid phone number.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('expects to throw a type error', () => {
|
||||||
|
expect(() => { formatPhoneNumber(12345) }).toThrow('Invalid phone number.')
|
||||||
|
})
|
||||||
|
})
|
Reference in New Issue
Block a user