Skip to content

Instantly share code, notes, and snippets.

@polarvogel
Last active February 14, 2018 00:20
Show Gist options
  • Save polarvogel/c328cf4fb76cf01753d49aff6a9fcffd to your computer and use it in GitHub Desktop.
Save polarvogel/c328cf4fb76cf01753d49aff6a9fcffd to your computer and use it in GitHub Desktop.
function getLuhnCheckDigit (number) {
var lastIndex = number.toString().length - 1 ;
var isOdd = true;
var sum = 0;
var curChar = '0';
var addValue = 0;
var multipliedDigit = 0;
number += "";
for (var n = lastIndex; n>=0; n--) {
curChar = number.charAt(n);
if (isOdd) {
multipliedDigit = curChar * 2;
if (multipliedDigit > 9) {
addValue = multipliedDigit - 9;
} else {
addValue = multipliedDigit;
}
} else {
addValue = curChar;
}
isOdd = !isOdd;
sum += parseInt(addValue);
}
return (10 - (sum % 10));
}
@polarvogel
Copy link
Author

polarvogel commented Feb 6, 2018

This is a JavaScript implementation to calculate the Luhn Check Digit of a given number

Beginning the most "right" / last number, every alternating number is multiplied by either 2 or 1. The result is added to the sum. If the multiplication result is >=10, then the digit sum will be added instead. The Luhn Check Digit is the difference between the sum and the next full multiple of 10.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment