@darthmaim/barcode
Version:
Verify EAN barcodes
42 lines • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.encode = exports.isValid = exports.checkdigit = void 0;
const helper_1 = require("./helper");
function checkdigit(value) {
const sum = value.substring(0, 7)
.split('')
.map((n) => Number(n))
.reduce((sum, digit, index) => {
return sum + (digit * (index % 2 ? 1 : 3));
});
return ((10 - (sum % 10)) % 10).toString();
}
exports.checkdigit = checkdigit;
const REGEX = /^[0-9]{8}$/;
function isValid(value) {
return REGEX.test(value) && checkdigit(value) === value[7];
}
exports.isValid = isValid;
function encode(value) {
if (!isValid(value)) {
throw new Error('Invalid EAN8 code');
}
const [left, right] = ['LLLL', 'RRRR'];
const leftValue = value.substring(0, 4);
const rightValue = value.substring(4, 8);
const groups = [
{ type: 'quietZone', width: 7 },
Object.assign({ type: 'marker' }, (0, helper_1.dataWithWidth)('101')),
Object.assign(Object.assign({ type: 'data' }, (0, helper_1.dataWithWidth)(leftValue.split('').map((digit, index) => helper_1.Encoding[digit][left[index]]).join(''))), { text: leftValue }),
Object.assign({ type: 'marker' }, (0, helper_1.dataWithWidth)('01010')),
Object.assign(Object.assign({ type: 'data' }, (0, helper_1.dataWithWidth)(rightValue.split('').map((digit, index) => helper_1.Encoding[digit][right[index]]).join(''))), { text: rightValue }),
Object.assign({ type: 'marker' }, (0, helper_1.dataWithWidth)('101')),
{ type: 'quietZone', width: 7 }
];
return {
width: groups.reduce((width, group) => width + group.width, 0),
groups,
};
}
exports.encode = encode;
//# sourceMappingURL=ean8.js.map