Skip to content

Instantly share code, notes, and snippets.

@rmela
Last active August 9, 2019 20:57
Show Gist options
  • Save rmela/71706082437984b076587c8a7b64095a to your computer and use it in GitHub Desktop.
Save rmela/71706082437984b076587c8a7b64095a to your computer and use it in GitHub Desktop.
GS1 checksum utilities
/*
*
* Wikipedia:
*
* The final digit of a Universal Product Code is a check digit computed as follows:
*
* 1) Take digits up to but not including the check digit.
* 2) Sum the digits in the odd-numbered positions (first, third, fifth, etc.) together and multiply by three.
* 3) Add the sum of digits in the even-numbered positions (0th, 2nd, 4th, 6th, etc.) to the result.
* 4) Take result modulo 10
* 5) If result is 0, return 0. Otherwise return 1 - result.
*
*/
function checksum(value) { // Generic GS1 checkdigit calculator ( ISBN, EAN, UPC, etc )
let d = value.split('')
.map( Number )
.map( (x,idx) => idx % 2 ? x * 3 : x )
.reduce( (accum, x ) => accum + x )
d = d % 10;
return d === 0 ? d : 10 - d;
}
function validate( code ) {
return code && code.slice(-1) == checksum(code.slice(0,-1));
}
function isUPC( code ) {
return validate(code) && code.length == 12;
}
module.exports = {
isUPC: isUPC,
validate: validate,
checksum: checksum
}
if( module.parent === null ) {
[
// 1234567890123
'9788131701713', // ISBN
'0011985810416',
'0038472368106',
'0751937198628',
'0068113106583',
'012345678905'
].forEach(
s => console.log( s, 'valid:', validate(s), 'len:', s.length )
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment