Skip to content

Instantly share code, notes, and snippets.

@wondersloth
Created January 9, 2015 19:11
Show Gist options
  • Save wondersloth/27700f91525b3cb416f7 to your computer and use it in GitHub Desktop.
Save wondersloth/27700f91525b3cb416f7 to your computer and use it in GitHub Desktop.
Validate Credit Card (Luhn Algorithm)
// 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