Published
Edited
May 25, 2021
1 fork
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require('d3')
Insert cell
Insert cell
function getUPCChecksum(nicNum) {
const nicWithoutCS = nicNum.substring(0, nicNum.length - 1);
const s = d3.sum(
d3.range(0, nicWithoutCS.length).map(function(i) {
if (i % 2 === 1) {
// Add the digits in the odd-numbered positions from the right
// (first, third, fifth, etc. - not including the check digit) together and multiply by three.
return parseInt(nicWithoutCS.charAt(i)) * 3;
} else {
// Add the digits (up to but not including the check digit) in the even-numbered positions
// (second, fourth, sixth, etc.) to the result.
return parseInt(nicWithoutCS.charAt(i));
}
})
);
console.debug(s);
// Take the remainder of the result divided by 10 (ie. the modulo 10 operation).
const rem = s % 10;

// If the remainder is equal to 0 then use 0 as the check digit,
if (rem === 0) {
return 0;
}
// and if not 0 subtract the remainder from 10 to derive the check digit.
return 10 - rem;
}
Insert cell
getUPCChecksum('036000241457')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more