Luhn check

JavaScript, Math, Algorithm · Jan 30, 2022

Implements the Luhn Algorithm used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.

const luhnCheck = num => {
  const arr = (num + '')
    .split('')
    .reverse()
    .map(x => parseInt(x));
  const lastDigit = arr.shift();
  let sum = arr.reduce(
    (acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val *= 2) > 9 ? val - 9 : val)),
    0
  );
  sum += lastDigit;
  return sum % 10 === 0;
};
luhnCheck('4485275742308327'); // true
luhnCheck(6011329933655299); //  true
luhnCheck(123456789); // false

More like this

  • JavaScript Algorithms

    Learn a handful of popular algorithms, implemented in JavaScript ES6.

    Collection · 35 snippets

  • Primes up to given number

    Generates primes up to a given number, using the Sieve of Eratosthenes.

    JavaScript, Math · Dec 28, 2020

  • Prime factors of number

    Finds the prime factors of a given number using the trial division algorithm.

    JavaScript, Math · Dec 28, 2020

  • Number is prime

    Checks if the provided integer is a prime number.

    JavaScript, Math · Jan 12, 2021