All files formatPhoneNumber.ts

100% Statements 20/20
100% Branches 6/6
100% Functions 1/1
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 291x   1x 11x 11x   11x 11x 51x 51x   51x 51x 51x   51x     11x 11x 11x       4x   11x    
const optionalLeadingNumber = '(0)';
 
export default function formatPhoneNumber(phoneNumber: string): string {
  phoneNumber = phoneNumber.replace(/[/. ()]/g, '');
  let size = 2;
 
  const parts: string[] = [];
  while (phoneNumber !== '') {
    if (parts.length === 3) size = 3;
    if (parts.length === 4) size = phoneNumber.length;
 
    const index = phoneNumber.length - size;
    const part = phoneNumber.substring(index);
    phoneNumber = phoneNumber.substring(0, index);
 
    parts.push(part);
  }
 
  const lastIndex = parts.length - 1;
  if (parts[lastIndex] === '0') parts[lastIndex] = optionalLeadingNumber;
  if (
    parts[lastIndex]!.length === 3 &&
    parts[lastIndex] !== optionalLeadingNumber
  )
    parts.push(optionalLeadingNumber);
 
  return parts.reverse().join(' ').trim();
}