Skip to content
This repository has been archived by the owner on Dec 13, 2021. It is now read-only.

Add phone utils #4

Merged
merged 1 commit into from
Sep 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/slimy-donkeys-float.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@thefakeorg/utils': patch
---

Add toPhoneE164 and fromPhoneE164 utilities
32 changes: 30 additions & 2 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
/**
* Return a slugified copy of a string.
*
* @param {string} str The string to be slugified
* @return {string} The slugified string.
* @param string - The string to be slugified
*/
export function toSlug(str: string): string {
let s = str;
Expand All @@ -17,3 +16,32 @@ export function toSlug(str: string): string {
s = s.length > 32 ? s.substr(0, 32) : s;
return s;
}

/**
* Convert a phone number from E.164 format into (212)-555-9656 format
* @param phone - An unformatted 12-digit phone number string
*/
export function fromPhoneE164(phone: string): string {
if (phone.length === 12) {
return (
phone.substring(2, 5) +
'-' +
phone.substring(5, 8) +
'-' +
phone.substring(8, 12)
);
} else {
return phone;
}
}

/**
* Convert a phone number into E.164 format.
*/
export function toPhoneE164(phone: string): string {
phone = phone.replace(/[^0-9]/g, '');
if (phone.length === 10) {
phone = '1' + phone;
}
return '+' + phone;
}