Skip to content

Commit c865654

Browse files
authored
Clean up phone number formatting (TheAlgorithms#1015)
1 parent f736217 commit c865654

File tree

2 files changed

+21
-30
lines changed

2 files changed

+21
-30
lines changed

‎String/FormatPhoneNumber.js‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
1-
// function that takes 10 digits and returns a string of the formatted phone number
2-
// e.g.: 1234567890 -> (123) 456-7890
3-
4-
constformatPhoneNumber=(numbers)=>{
5-
constnumbersString=numbers.toString()
6-
if((numbersString.length!==10)||isNaN(numbersString)){
1+
/**
2+
* @description - function that takes 10 digits and returns a string of the formatted phone number e.g.: 1234567890 -> (123) 456-7890
3+
* @param{string} phoneNumber
4+
* @returns{string} - Format to (XXX) XXX-XXXX pattern
5+
*/
6+
constformatPhoneNumber=(phoneNumber)=>{
7+
if((phoneNumber.length!==10)||isNaN(phoneNumber)){
78
// return "Invalid phone number."
8-
thrownewTypeError('Invalid phone number.')
9+
thrownewTypeError('Invalid phone number!')
910
}
10-
constarr='(XXX) XXX-XXXX'.split('')
11-
Array.from(numbersString).forEach(n=>{
12-
arr[arr.indexOf('X')]=n
13-
})
14-
returnarr.join('')
11+
12+
letindex=0
13+
return'(XXX) XXX-XXXX'.replace(/X/g,()=>phoneNumber[index++])
1514
}
1615

17-
export{formatPhoneNumber}
16+
exportdefaultformatPhoneNumber
Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,15 @@
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-
})
1+
importformatPhoneNumberfrom'../FormatPhoneNumber'
112

3+
describe('Testing the formatPhoneNumber functions',()=>{
124
it('expects to throw a type error',()=>{
13-
expect(()=>{formatPhoneNumber('1234567')}).toThrow('Invalid phone number.')
5+
expect(()=>formatPhoneNumber('1234567')).toThrow('Invalid phone number!')
6+
expect(()=>formatPhoneNumber('123456text')).toThrow('Invalid phone number!')
7+
expect(()=>formatPhoneNumber(12345)).toThrow('Invalid phone number!')
148
})
159

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.')
10+
it('expects to return the formatted phone number',()=>{
11+
expect(formatPhoneNumber('1234567890')).toEqual('(123) 456-7890')
12+
expect(formatPhoneNumber('2124323322')).toEqual('(212) 432-3322')
13+
expect(formatPhoneNumber('1721543455')).toEqual('(172) 154-3455')
2214
})
2315
})

0 commit comments

Comments
(0)