Drill

ProblemsJavaScript › payments

Luhn check a card number

mediumpaymentsJavaScript

Before a card ever reaches the payment gateway, the checkout runs the Luhn checksum so an obvious typo is caught in the browser.

luhnValid(digits: string) → bool

Solve it in the editor →

Where you start

function luhnValid(digits) {
  
}

Worked examples

CallResult
luhnValid("79927398713")true
luhnValid("79927398710")false
luhnValid("4111 1111 1111 1111")true
luhnValid("4111-1111-1111-1112")false

Hint

Strip the formatting into a clean string first. Then walk it backwards with an index so "every second" is easy to say.

Reference solution in JavaScript
function luhnValid(digits) {
  let clean = '';
  for (const c of digits) {
    if (c === ' ' || c === '-') continue;
    if (c < '0' || c > '9') return false;
    clean += c;
  }
  if (clean.length < 2) return false;
  let sum = 0;
  for (let i = 0; i < clean.length; i++) {
    let d = clean.charCodeAt(clean.length - 1 - i) - 48;
    if (i % 2 === 1) { d *= 2; if (d > 9) d -= 9; }
    sum += d;
  }
  return sum % 10 === 0;
}

The same problem in another language

More payments problems in JavaScript