Created
November 28, 2016 17:50
-
-
Save droberts-sea/cf8852f20c4d607194308c5244101c6b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var Luhn = function(number) { | |
// console.log("Doing Luhn check on " + number); | |
this.checkDigit = number % 10; | |
this.addends = []; | |
this.checksum = 0; | |
// for (var i = 1; number > 0; i++) { | |
// var i = 1; | |
var double = false; | |
while (number > 0) { | |
// Extract the last digit | |
var digit = number % 10; | |
// Double even-counted digits | |
if (double) { | |
digit *= 2; | |
// If the result >= 10, subtract 9 | |
if (digit >= 10) { | |
digit -= 9; | |
} | |
} | |
// console.log(digit); | |
this.checksum += digit; | |
this.addends.unshift(digit); | |
number = Math.floor(number / 10); | |
double = !double; | |
// i++; | |
} | |
this.valid = this.checksum % 10 == 0; | |
} | |
Luhn.create = function(number) { | |
number *= 10; | |
var luhnResult = new Luhn(number); | |
if (luhnResult.valid) { | |
return number; | |
} | |
var checksum = luhnResult.checksum; | |
var addend = 10 - (checksum % 10); | |
return number + addend; | |
}; | |
module.exports = Luhn; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment