Last active
July 3, 2018 14:01
-
-
Save kepek/d6bdadbf7b13174e1960057e9bd1926b to your computer and use it in GitHub Desktop.
Generate check digit for UPC-A
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
function checkDigit(value) { | |
value = value.toString(); | |
var checkDigit = 0, | |
evens = 0, | |
odds = 0, | |
checkDigit = 0; | |
for (var i = 0; i < value.length; i++) { | |
// For zero-based arrays, odd digits are even indexes | |
if (i % 2) { | |
evens += parseInt(value[i], 10); | |
} else { | |
odds += parseInt(value[i], 10); | |
} | |
} | |
// Multiply odds by 3, add to evens. | |
// Subtract the modulo of that sum from 10 | |
checkDigit = 10 - (((odds * 3) + evens) % 10); | |
// If checksum is 10, just use zero | |
checkDigit = (checkDigit == 10) ? 0 : checkDigit; | |
return checkDigit | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment