Lines of Code | 63 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | // Encoding documentation: |
||
4 | import { SIDE_BIN, MIDDLE_BIN } from './constants'; |
||
5 | import encode from './encoder'; |
||
6 | import Barcode from "../Barcode"; |
||
7 | |||
8 | // Calculate the checksum digit |
||
9 | const checksum = (number) => { |
||
10 | const res = number |
||
11 | .substr(0, 7) |
||
12 | .split('') |
||
13 | .map((n) => +n) |
||
14 | .reduce((sum, a, idx) => { |
||
15 | return idx % 2 |
||
16 | ? sum + a |
||
17 | : sum + a * 3; |
||
18 | }, 0); |
||
19 | |||
20 | return (10 - (res % 10)) % 10; |
||
21 | }; |
||
22 | |||
23 | class EAN8 extends Barcode { |
||
24 | |||
25 | constructor(data, options) { |
||
26 | // Add checksum if it does not exist |
||
27 | if(data.search(/^[0-9]{7}$/) !== -1){ |
||
28 | data += checksum(data); |
||
29 | } |
||
30 | |||
31 | super(data, options); |
||
32 | } |
||
33 | |||
34 | valid() { |
||
35 | return ( |
||
36 | this.data.search(/^[0-9]{8}$/) !== -1 && |
||
37 | +this.data[7] === checksum(this.data) |
||
38 | ); |
||
39 | } |
||
40 | |||
41 | get leftData() { |
||
42 | return this.data.substr(0, 4); |
||
43 | } |
||
44 | |||
45 | get rightData() { |
||
46 | return this.data.substr(4, 4); |
||
47 | } |
||
48 | |||
49 | encode() { |
||
50 | const data = [ |
||
51 | SIDE_BIN, |
||
52 | encode(this.leftData, 'LLLL'), |
||
53 | MIDDLE_BIN, |
||
54 | encode(this.rightData, 'RRRR'), |
||
55 | SIDE_BIN, |
||
56 | ]; |
||
57 | |||
58 | return { |
||
59 | data: data.join(''), |
||
60 | text: this.text |
||
61 | }; |
||
62 | } |
||
63 | |||
64 | } |
||
65 | |||
66 | export default EAN8; |
||
67 |