Skip to content

Instantly share code, notes, and snippets.

@DiegoSalazar
Last active April 24, 2024 12:51
Show Gist options
  • Save DiegoSalazar/4075533 to your computer and use it in GitHub Desktop.
Save DiegoSalazar/4075533 to your computer and use it in GitHub Desktop.
Luhn algorithm in Javascript. Check valid credit card numbers
// Takes a credit card string value and returns true on valid number
function valid_credit_card(value) {
// Accept only digits, dashes or spaces
if (/[^0-9-\s]+/.test(value)) return false;
// The Luhn Algorithm. It's so pretty.
let nCheck = 0, bEven = false;
value = value.replace(/\D/g, "");
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven && (nDigit *= 2) > 9) nDigit -= 9;
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
@asfo
Copy link

asfo commented Feb 24, 2023

A shitty one-liner:

const luhn = numbers => numbers.split('').map((value, index) => index % 2 === 0 ? Number(value) * 2 <= 9 ? Number(value) * 2 : Number(Number(`${Number(value) * 2}`.split('')[0]) + Number(`${Number(value) * 2}`.split('')[1])) : Number(value)).reduce((a, b) => a + b).toString().split('')[1] === '0';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment