Skip to content

Instantly share code, notes, and snippets.

@wmakeev
Created March 15, 2024 10:00
Show Gist options
  • Save wmakeev/4f12413b8b222efe256c991fccb1c571 to your computer and use it in GitHub Desktop.
Save wmakeev/4f12413b8b222efe256c991fccb1c571 to your computer and use it in GitHub Desktop.
[barcode] #barcode #gtin #ean
/**
* Check if code is EAN13
*
* @link https://github.com/hampus-nilsson/gs1-checkdigit/blob/main/checkdigit.js
* @param {string} input
* @returns {boolean}
*/
export function isGTIN(input) {
if (![8, 12, 13, 14].includes(input.length)) return false;
const digs = input.split("").reverse();
let total = 0;
for (let i = 1; i < digs.length; i++) {
const num = parseInt(
// @ts-expect-error skip
digs[i]
);
if (Number.isNaN(num)) return false;
if (i % 2 === 0) {
total += num;
} else {
total += num * 3;
}
}
const check = Math.ceil(total / 10) * 10 - total;
// @ts-expect-error skip
return parseInt(digs[0]) === check;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment