From 9f2eaea0852bc51eee230387aeb5d6b045d3db69 Mon Sep 17 00:00:00 2001 From: Ulad Kasach Date: Tue, 3 Dec 2024 03:48:41 -0800 Subject: [PATCH] feat(cast): cast to phone in human words --- src/asUniPhoneInHumanWords.test.ts | 11 +++++++++++ src/asUniPhoneInHumanWords.ts | 24 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 src/asUniPhoneInHumanWords.test.ts create mode 100644 src/asUniPhoneInHumanWords.ts diff --git a/src/asUniPhoneInHumanWords.test.ts b/src/asUniPhoneInHumanWords.test.ts new file mode 100644 index 0000000..ab86065 --- /dev/null +++ b/src/asUniPhoneInHumanWords.test.ts @@ -0,0 +1,11 @@ +import { asUniPhoneInHumanWords } from './asUniPhoneInHumanWords'; +import { isUniPhoneNumber } from './isUniPhoneNumber'; + +describe('asUniPhoneInHumanWords', () => { + it('should look right', () => { + const result = asUniPhoneInHumanWords({ + number: isUniPhoneNumber.assure('+13175557777'), + }); + expect(result).toEqual('(317) 555-7777'); + }); +}); diff --git a/src/asUniPhoneInHumanWords.ts b/src/asUniPhoneInHumanWords.ts new file mode 100644 index 0000000..e516ff9 --- /dev/null +++ b/src/asUniPhoneInHumanWords.ts @@ -0,0 +1,24 @@ +import { UniPhone } from './UniPhone'; + +/** + * .what = casts a uni phone into human words + * .example + * - +13335557777 => (333) 555-7777 + */ +export const asUniPhoneInHumanWords = (input: UniPhone): string => { + // Validate input: must start with '+' followed by digits + const phoneRegex = /^\+(\d{1,3})(\d{3})(\d{3})(\d{4})$/; + const match = input.number.match(phoneRegex); + + if (!match) { + throw new Error( + 'Invalid UniPhone format. Expected format: +<10-digit-phone>', + ); + } + + // Extract groups + const [, , areaCode, centralOfficeCode, lineNumber] = match; + + // Format the phone number + return `(${areaCode}) ${centralOfficeCode}-${lineNumber}`; +};