Skip to content

Instantly share code, notes, and snippets.

@kepek
Last active July 3, 2018 14:01
Show Gist options
  • Save kepek/d6bdadbf7b13174e1960057e9bd1926b to your computer and use it in GitHub Desktop.
Save kepek/d6bdadbf7b13174e1960057e9bd1926b to your computer and use it in GitHub Desktop.
Generate check digit for UPC-A
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