Created
March 15, 2024 10:00
-
-
Save wmakeev/4f12413b8b222efe256c991fccb1c571 to your computer and use it in GitHub Desktop.
[barcode] #barcode #gtin #ean
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
/** | |
* 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