Skip to content

Instantly share code, notes, and snippets.

@Yurko-Fedoriv
Created February 28, 2019 15:49
Show Gist options
  • Save Yurko-Fedoriv/547287e3cc0f78c11354b99d72debfcf to your computer and use it in GitHub Desktop.
Save Yurko-Fedoriv/547287e3cc0f78c11354b99d72debfcf to your computer and use it in GitHub Desktop.
UPC check digit function that validates the check digit on a UPC
function reverse(string) {
return string
.split('')
.reverse()
.join('');
}
// function to calculate EAN / UPC checkdigit
function eanCheckDigit(s) {
var result = 0;
var rs = reverse(s);
for (var counter = 0; counter < rs.length; counter++) {
result = result + parseInt(rs.charAt(counter)) * Math.pow(3, ((counter + 1) % 2));
}
return (10 - (result % 10)) % 10;
}
function checksum(s) {
return s ? eanCheckDigit(s.slice(0, -1)) === Number(s.slice(-1)) : false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment