Skip to content

Instantly share code, notes, and snippets.

@yavgel85
Created March 26, 2021 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yavgel85/1530da6e5cbf9e58f96288b38b226612 to your computer and use it in GitHub Desktop.
Save yavgel85/1530da6e5cbf9e58f96288b38b226612 to your computer and use it in GitHub Desktop.
luhnCheck #js #algorithm
// Implementation of the Luhn Algorithm used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.
// Use String.prototype.split(''), Array.prototype.reverse() and Array.prototype.map() in combination with parseInt() to obtain an array of digits.
// Use Array.prototype.splice(0, 1) to obtain the last digit.
// Use Array.prototype.reduce() to implement the Luhn Algorithm.
// Return true if sum is divisible by 10, false otherwise.
const luhnCheck = num => {
let arr = (num + '')
.split('')
.reverse()
.map(x => parseInt(x));
let lastDigit = arr.splice(0, 1)[0];
let sum = arr.reduce(
(acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9),
0
);
sum += lastDigit;
return sum % 10 === 0;
};
// Examples
luhnCheck('4485275742308327'); // true
luhnCheck(6011329933655299); // false
luhnCheck(123456789); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment