Skip to content

Instantly share code, notes, and snippets.

@A1rPun
Last active December 18, 2019 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A1rPun/f618aa8ad4cb949d4f7241ba1579c889 to your computer and use it in GitHub Desktop.
Save A1rPun/f618aa8ad4cb949d4f7241ba1579c889 to your computer and use it in GitHub Desktop.
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