Created
October 20, 2023 14:29
-
-
Save danieloneill/6b9e32428d0b0f20f2df1618f76fa9fb to your computer and use it in GitHub Desktop.
GS1 GTIN-14 check bit calculation in JS, RFC
This file contains hidden or 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 checksum(gtin) | |
{ | |
const len = gtin.length; | |
// Split the code into an array of characters | |
// then map that into an array of numbers: | |
const chs = gtin.split('').map( (e) => parseInt(e) ); | |
// Since this is just a GTIN-14 example: | |
if( 14 === len ) | |
{ | |
// 12345678901234 | |
// 00842650000272 | |
// The GS1 AI (01) is stripped (obv). | |
// Padding that was removed (leading 00) is added back | |
// Technically the evens (odd array positions) are multiplied by 1, | |
// but according to my Grade 1 maths class... we good. | |
// This could be put in a loop, but this is clear and not too long imo: | |
let sum = 0; | |
sum += chs[0] * 3; | |
sum += chs[1]; | |
sum += chs[2] * 3; | |
sum += chs[3]; | |
sum += chs[4] * 3; | |
sum += chs[5]; | |
sum += chs[6] * 3; | |
sum += chs[7]; | |
sum += chs[8] * 3; | |
sum += chs[9]; | |
sum += chs[10] * 3; | |
sum += chs[11]; | |
sum += chs[12] * 3; | |
// Per GS1 spec: "Subtract sum from nearest equal or higher multiple of ten" | |
// But we can modulo and subtract that for the right answer: | |
const chk = 10 - (sum % 10); | |
return chs[13] === chk; | |
} | |
/* Here you'd also want to check GTIN-13, GTIN-12, and GTIN-8. | |
* | |
* For GTIN-12 and GTIN-8 you can just pad the left with zeros | |
* to "make" them a GTIN-14, but not for GTIN-13 as the check | |
* value would change, since it works on opposite fields to | |
* the rest. | |
* | |
* If in doubt, just follow 7.9.1 of the spec. | |
*/ | |
return false; | |
} |
Author
danieloneill
commented
Oct 20, 2023
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment