Last active
December 18, 2019 22:22
-
-
Save A1rPun/f618aa8ad4cb949d4f7241ba1579c889 to your computer and use it in GitHub Desktop.
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
const GTIN_SSCC_LENGTH = 16; | |
const WEIGHT_EVEN = 3; | |
const WEIGHT_ODD = 1; | |
function ceil(n, base) { | |
// TODO: 0.1, 0.01, 0.001, etc. | |
return Math.ceil(n / base) * base; | |
} | |
function validateEan(str = '') { | |
const digits = str.padStart(GTIN_SSCC_LENGTH, '0').split(''); | |
const validationCode = parseInt(digits.pop()); | |
const checksum = digits.reduce((acc, cur, i) => | |
acc + (i % 2 === 0 | |
? WEIGHT_EVEN * cur | |
: WEIGHT_ODD * cur), | |
0 | |
); | |
const nearestChecksum = ceil(checksum, 10); | |
return nearestChecksum - checksum === validationCode; | |
} | |
console.log(validateEan('1337133713379')); // false | |
console.log(validateEan('1337133713378')); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment