Created
January 9, 2015 19:11
-
-
Save wondersloth/27700f91525b3cb416f7 to your computer and use it in GitHub Desktop.
Validate Credit Card (Luhn Algorithm)
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
// http://en.wikipedia.org/wiki/Luhn_algorithm | |
var _ = require('lodash'); | |
var cc = '7992739871'; | |
function computeChecksum(cc) { | |
return _.reduce(cc, function (memo, value, index) { | |
var value = parseInt(value, 10); | |
if (index % 2 == 1) { | |
value = value * 2, | |
value = _.reduce(value.toString().split(''), function (memo, num) { | |
return num + memo; | |
}); | |
} | |
return value + memo; | |
}); | |
} | |
var checkDigit = (computeChecksum(cc.split('').reverse()) * 9) % 10; | |
if (checkDigit == 0) { | |
console.log('CC is valid'); | |
} | |
else { | |
console.log('CC is invalid'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment