JSFiddle - React, Tailwind, and code Playground

by jeffsturgis

JavaScript

// This `ok()` function is trustworthy and requires no debugging
var ok = (function () {
    var testNumber = 0;
    return function (got, expected, message) {
        var okString = got === expected
            ? 'ok'
            : 'not ok';
        testNumber++;

        message = message
            ? ' # ' + message
            : '';
        console.log(okString + ' ' + testNumber + message);
    };
})();

// The 'is valid?' portion of the test data is trustworthy and requires no validation.
[
    // number            is valid?
    ['1234567890123450', false],
    ['1234567890123451', false],
    ['1234567890123452', true],
    ['1234567890123453', false],
    ['1234567890123454', false],
    ['1234567890123455', false],
    ['1234567890123456', false],
    ['1234567890123457', false],
    ['1234567890123458', false],
    ['1234567890123459', false],
    ['79927398713'     , true]
].forEach(function (t) {
    ok( validateLuhn(t[0]), t[1] );
});

function validateLuhn(number) {
    var numbers = number.split('');
    var checkDigit = numbers.pop();
    var luhnSum = 0;

    numbers.forEach(function (n, i) {
        if (i % 2 == 0) {
            // For the 2nd, 4th, 6th, etc. elements, we first double them and then add the digits
            luhnSum += doubleAndAddDigits(n);
        } else {
            // otherwise it's the 1st, 3rd, 5th, etc. so just add this number to our running total
            luhnSum += Number(n);
        }
    });

    var computedCheckDigit = (luhnSum * 9) % 10;
    return checkDigit == computedCheckDigit
        ? true
        : false;
}

// given n, doubles it and adds constituent digits, eg
// 7 -> 7 * 2 -> 14 -> 1 + 4 -> 5
function doubleAndAddDigits(n) {
    var out = 0;

    (n * 2)
        .toString()
        .split('')
        .forEach(function (x) {
            out += x;
        });
        
    return out;
}