Menu

gitpiper

luhnCheck javascript Code Snippet in 2024

mathalgorithmadvanced

Last Updated: 17 December 2024

Implements 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 ? val - 9 : val)), 0 ); sum += lastDigit; return sum % 10 === 0; };
luhnCheck('4485275742308327'); // true luhnCheck(6011329933655299); // true luhnCheck(123456789); // false

javascript snippet similar to luhnCheck For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️