UNPKG

@darthmaim/barcode

Version:
54 lines 2.14 kB
"use strict"; 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, 12) .split('') .map((n) => Number(n)) .reduce((sum, digit, index) => { return sum + (digit * (index % 2 ? 3 : 1)); }); return ((10 - (sum % 10)) % 10).toString(); } exports.checkdigit = checkdigit; const REGEX = /^[0-9]{13}$/; function isValid(value) { return REGEX.test(value) && checkdigit(value) === value[12]; } exports.isValid = isValid; function encode(value) { if (!isValid(value)) { throw new Error('Invalid EAN13 code'); } const [left, right] = Structure[value[0]]; const leftValue = value.substring(1, 7); const rightValue = value.substring(7, 13); const groups = [ { type: 'quietZone', text: value[0], width: 11 }, 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; const Structure = { '0': ['LLLLLL', 'RRRRRR'], '1': ['LLGLGG', 'RRRRRR'], '2': ['LLGGLG', 'RRRRRR'], '3': ['LLGGGL', 'RRRRRR'], '4': ['LGLLGG', 'RRRRRR'], '5': ['LGGLLG', 'RRRRRR'], '6': ['LGGGLL', 'RRRRRR'], '7': ['LGLGLG', 'RRRRRR'], '8': ['LGLGGL', 'RRRRRR'], '9': ['LGGLGL', 'RRRRRR'], }; //# sourceMappingURL=ean13.js.map