Skip to content

Instantly share code, notes, and snippets.

@ekoeryanto
Last active December 24, 2021 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekoeryanto/8c773aed44857e4daa22d423f764703e to your computer and use it in GitHub Desktop.
Save ekoeryanto/8c773aed44857e4daa22d423f764703e to your computer and use it in GitHub Desktop.
format phone number
import {Phonetic} from './phonetic';
describe('convert phone number to local number', () => {
const phonetic = new Phonetic('62');
test('international code with plus', () => {
expect(phonetic.localize('+628123')).toEqual('08123');
});
test('international code with plus and leading zero', () => {
expect(phonetic.localize('+6208123')).toEqual('08123');
});
test('international code with plus and leading zeroes', () => {
expect(phonetic.localize('+62000000008123')).toEqual('08123');
});
test('international to local', () => {
expect(phonetic.localize('628123')).toEqual('08123');
});
test('international code with leading zeroes to local', () => {
expect(phonetic.localize('62000000008123')).toEqual('08123');
});
});
describe('convert phone number to international number', () => {
const phonetic = new Phonetic('62');
test('normal local number', () => {
expect(phonetic.internationalize('08123')).toEqual('628123');
});
test('number with no zero', () => {
expect(phonetic.internationalize('8123')).toEqual('628123');
});
test('number with same prefix', () => {
expect(phonetic.internationalize('628123')).toEqual('628123');
});
test('leading zeroes', () => {
expect(phonetic.internationalize('00008123')).toEqual('628123');
});
});
export class Phonetic {
private plainPrefix: string;
constructor(private prefix: string) {
this.plainPrefix = this.numberize(prefix);
}
private numberize(phone: string) {
return phone.replace(/\D+/g, '');
}
localize(phone: string) {
const ph = this.numberize(phone);
if (!ph || ph.startsWith('0')) {
return ph;
}
const matcher = new RegExp(`^${this.plainPrefix}(?:0+(?=[1-9])|0+(?=0$))?`);
return ph.replace(matcher, '0');
}
internationalize(phone: string) {
let ph = this.numberize(phone);
if (!ph || ph.startsWith(this.plainPrefix)) {
return ph;
}
if (ph.startsWith('0')) {
return ph.replace(/^0+/, this.plainPrefix);
}
return this.plainPrefix + ph;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment