Skip to content

Commit ba3af82

Browse files
committed
Add Phone Number Formatting Function
1 parent e92b5d2 commit ba3af82

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

String/FormatPhoneNumber.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// function that takes 10 digits and returns a string of the formatted phone number
2+
// e.g.: 1234567890 -> (123) 456-7890
3+
4+
const formatPhoneNumber = (numbers) => {
5+
const numbersString = numbers.toString()
6+
if ((numbersString.length !== 10) || isNaN(numbersString)) {
7+
// return "Invalid phone number."
8+
throw new TypeError('Invalid phone number.')
9+
}
10+
const arr = '(XXX) XXX-XXXX'.split('')
11+
Array.from(numbersString).forEach(n => {
12+
arr[arr.indexOf('X')] = n
13+
})
14+
return arr.join('')
15+
}
16+
17+
export { formatPhoneNumber }

String/FormatPhoneNumber.test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { formatPhoneNumber } from './FormatPhoneNumber'
2+
3+
describe('PhoneNumberFormatting', () => {
4+
it('expects to return the formatted phone number', () => {
5+
expect(formatPhoneNumber('1234567890')).toEqual('(123) 456-7890')
6+
})
7+
8+
it('expects to return the formatted phone number', () => {
9+
expect(formatPhoneNumber(1234567890)).toEqual('(123) 456-7890')
10+
})
11+
12+
it('expects to throw a type error', () => {
13+
expect(() => { formatPhoneNumber('1234567') }).toThrow('Invalid phone number.')
14+
})
15+
16+
it('expects to throw a type error', () => {
17+
expect(() => { formatPhoneNumber('123456text') }).toThrow('Invalid phone number.')
18+
})
19+
20+
it('expects to throw a type error', () => {
21+
expect(() => { formatPhoneNumber(12345) }).toThrow('Invalid phone number.')
22+
})
23+
})

0 commit comments

Comments
 (0)