Skip to content

Instantly share code, notes, and snippets.

@danieloneill
Created October 20, 2023 14:29
Show Gist options
  • Save danieloneill/6b9e32428d0b0f20f2df1618f76fa9fb to your computer and use it in GitHub Desktop.
Save danieloneill/6b9e32428d0b0f20f2df1618f76fa9fb to your computer and use it in GitHub Desktop.
GS1 GTIN-14 check bit calculation in JS, RFC
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;
}
@danieloneill
Copy link
Author

danieloneill commented Oct 20, 2023

    // smoller-boi:
    function checksum(gtin)
    {
        const chs = gtin.split('').map( (e) => parseInt(e) );

        let sum = 0;
        for( let a=0; a < chs.length-1; a++ )
            sum += ( a % 2 === 1 ? chs[a] : chs[a] * 3 );

        const chk = 10 - (sum % 10);
        return chs[chs.length-1] === chk;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment