Skip to content

Commit

Permalink
feat(cast): cast to phone in human words
Browse files Browse the repository at this point in the history
  • Loading branch information
uladkasach committed Dec 3, 2024
1 parent 34b2491 commit 9f2eaea
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/asUniPhoneInHumanWords.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
24 changes: 24 additions & 0 deletions src/asUniPhoneInHumanWords.ts
Original file line number Diff line number Diff line change
@@ -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: +<country-code><10-digit-phone>',
);
}

// Extract groups
const [, , areaCode, centralOfficeCode, lineNumber] = match;

// Format the phone number
return `(${areaCode}) ${centralOfficeCode}-${lineNumber}`;
};

0 comments on commit 9f2eaea

Please sign in to comment.