ts-barcode-generator
Version:
Simple Barcode Generator created in TypeScript
64 lines (63 loc) • 1.85 kB
JavaScript
import { convertBinaryStringToArray, convertToPairs, generateSimpleSvg1D } from '../utils';
class EAN13 {
static calculateParity(data) {
const leftDigits = data.slice(0, 6);
const rightDigits = data.slice(6);
const leftParity = leftDigits
.split('')
.map((digit) => this.LEFT_PARITY[digit])
.join('');
const rightParity = rightDigits
.split('')
.map((digit) => this.RIGHT_PARITY[digit])
.join('');
return leftParity + this.MIDDLE_MARKER + rightParity;
}
static generateBinaryRepresentation(data) {
const parityData = this.calculateParity(data);
return (this.START_MARKER +
parityData +
this.END_MARKER);
}
static Generate(data) {
const binaryRepresentation = this.generateBinaryRepresentation(data);
const arrayRepresentation = convertBinaryStringToArray(binaryRepresentation);
const groupedPairs = convertToPairs(arrayRepresentation);
const svg = generateSimpleSvg1D(groupedPairs);
return svg;
}
static generate(data) {
if (!/^\d{12,13}$/.test(data)) {
throw new Error('EAN-13 must be 12 digits.');
}
return this.Generate(data);
}
}
EAN13.START_MARKER = '101';
EAN13.MIDDLE_MARKER = '01010';
EAN13.END_MARKER = '101';
EAN13.LEFT_PARITY = {
'0': '0001101',
'1': '0011001',
'2': '0010011',
'3': '0111101',
'4': '0100011',
'5': '0110001',
'6': '0101111',
'7': '0111011',
'8': '0110111',
'9': '0001011',
};
EAN13.RIGHT_PARITY = {
'0': '1110010',
'1': '1100110',
'2': '1101100',
'3': '1000010',
'4': '1011100',
'5': '1001110',
'6': '1010000',
'7': '1000100',
'8': '1001000',
'9': '1110100',
};
export default EAN13;