What you're building
A LuhnValidator that implements the Luhn algorithm — the checksum used to catch transposition errors in credit card numbers, IMEI codes, and national IDs.
Requirements
isValid(cardNumber)— accepts a string (may contain spaces or dashes, strip them first). Returnstrueif the number passes the Luhn check,falseotherwise.getCheckDigit(partialNumber)— given a card number with the last digit missing (or0), compute and return the correct check digit as a number.sanitize(input)— strips all non-digit characters and returns the resulting string.
The Luhn Algorithm
- Starting from the rightmost digit (the check digit), move left.
- Double every second digit (i.e. every digit at an even index from the right, skipping index 0).
- If doubling produces a value > 9, subtract 9.
- Sum all digits.
- If the total modulo 10 equals 0, the number is valid.
Example: "4532015112830366" is a valid Luhn number.
Stretch goals
- Detect the card brand (Visa starts with 4, Mastercard 51-55, Amex 34/37).
- Validate that the number has the correct length for its detected brand.
What this proves
Bit-manipulation thinking, off-by-one awareness, and working from a written specification — exactly what technical screens test.
⚡ 50 XP
solution.jsRuns in your browser
Loading editor…
Tests4 to pass
known valid card numbers pass
tampered number fails
sanitize strips non-digits
getCheckDigit finds correct digit
Run your code to check these.