All files / src payment.js

100% Statements 35/35
100% Branches 22/22
100% Functions 6/6
100% Lines 27/27

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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45  89x       45x 45x 36x 15x 11x       13x 13x   9x 9x 33x   13x 13x 13x 32x 30x 30x   9x       10x 10x 9x 9x 7x 7x       21x 21x 21x    
function onlyDigits(value) {
  return String(value ?? '').replace(/\D/g, '');
}
 
export function detectCardBrand(number) {
  const digits = onlyDigits(number);
  if (/^3[47]/.test(digits)) return 'amex';
  if (/^4/.test(digits)) return 'visa';
  if (/^(5[1-5]|222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)/.test(digits)) return 'mastercard';
  return null;
}
 
export function formatCardNumber(number) {
  const digits = onlyDigits(number);
  if (!digits) return '';
 
  const amex = detectCardBrand(digits) === 'amex';
  const groups = amex ? [4, 6, 5] : [4, 4, 4, 4];
  const capped = digits.slice(0, groups.reduce((total, size) => total + size, 0));
 
  const parts = [];
  let index = 0;
  for (const size of groups) {
    if (index >= capped.length) break;
    parts.push(capped.slice(index, index + size));
    index += size;
  }
  return parts.join(' ');
}
 
export function formatExpiry(input) {
  const digits = onlyDigits(input);
  if (digits.length === 0) return '';
  const month = digits.slice(0, 2);
  if (digits.length < 3) return month;
  const year = digits.slice(2, 6);
  return `${month}/${year.length === 4 ? year.slice(2) : year}`;
}
 
export function isCardNumberComplete(number, brand) {
  const digits = onlyDigits(number);
  const expected = brand === 'amex' ? 15 : 16;
  return digits.length === expected;
}