Created
March 19, 2013 15:42
-
-
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.
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
<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