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()
andArray.prototype.map()
in combination withparseInt()
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
ifsum
is divisible by10
,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
Recommended snippets
Generates primes up to a given number, using the Sieve of Eratosthenes.
Initializes an array containing the numbers in the specified range where
start
andend
are inclusive and the ratio between two terms isstep
. Returns an error ifstep
equals1
.Finds the prime factors of a given number using the trial division algorithm.