Last active
February 14, 2018 00:20
-
-
Save polarvogel/c328cf4fb76cf01753d49aff6a9fcffd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.