From ba3af82e847e405e5bdc70c019ac23e62e8bf5cb Mon Sep 17 00:00:00 2001 From: aladin002dz Date: Wed, 7 Oct 2020 11:37:42 +0100 Subject: [PATCH] Add Phone Number Formatting Function --- String/FormatPhoneNumber.js | 17 +++++++++++++++++ String/FormatPhoneNumber.test.js | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 String/FormatPhoneNumber.js create mode 100644 String/FormatPhoneNumber.test.js diff --git a/String/FormatPhoneNumber.js b/String/FormatPhoneNumber.js new file mode 100644 index 000000000..c1bbde832 --- /dev/null +++ b/String/FormatPhoneNumber.js @@ -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 } diff --git a/String/FormatPhoneNumber.test.js b/String/FormatPhoneNumber.test.js new file mode 100644 index 000000000..85291b84c --- /dev/null +++ b/String/FormatPhoneNumber.test.js @@ -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.') + }) +})