Skip to content

Instantly share code, notes, and snippets.

@defiant
Created March 19, 2013 15:42
Show Gist options
  • Save defiant/5197159 to your computer and use it in GitHub Desktop.
Save defiant/5197159 to your computer and use it in GitHub Desktop.
Simple JS function. Returns true or false if the giving string passes Luhn Algorithm requirements.
<script>
var luhnNo = '79927398711';
function luhn(num){
var numArr = num.split(''),
tempInt,
odd = 0,
even = 0;
numArr.reverse();
for (var i = 0; i < numArr.length; i++) {
if (i % 2 != 0) {
//even
tempInt = parseInt(numArr[i], 10) * 2;
var y;
if (tempInt<9) {
even += parseInt(tempInt, 10);
}else{
var x = '' + tempInt;
even += parseInt(x.charAt(0), 10) + parseInt(x.charAt(1), 10);
}
}else{
//odd
odd += parseInt(numArr[i], 10);
}
};
return (odd + even) % 10 ? true : false;
}
console.log(luhn(luhnNo));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment