Created
February 28, 2019 15:49
-
-
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
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 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