Completed
Pull Request — master (#226)
by
unknown
22s
created

EAN8.js ➔ ... ➔ ???   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 1
rs 10
1
// Encoding documentation:
2
// http://www.barcodeisland.com/ean8.phtml
3
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
			idx % 2 ? sum + a : sum + a * 3
16
		), 0);
17
18
	return (10 - (res % 10)) % 10;
19
};
20
21
class EAN8 extends Barcode {
22
23
	constructor(data, options) {
24
		// Add checksum if it does not exist
25
		if(data.search(/^[0-9]{7}$/) !== -1){
26
			data += checksum(data);
27
		}
28
29
		super(data, options);
30
	}
31
32
	valid() {
33
		return (
34
			this.data.search(/^[0-9]{8}$/) !== -1 &&
35
			+this.data[7] === checksum(this.data)
36
		);
37
	}
38
39
	get leftData() {
40
		return this.data.substr(0, 4);
41
	}
42
43
	get rightData() {
44
		return this.data.substr(4, 4);
45
	}
46
47
	encode() {
48
		const data = [
49
			SIDE_BIN,
50
			encode(this.leftData, 'LLLL'),
51
			MIDDLE_BIN,
52
			encode(this.rightData, 'RRRR'),
53
			SIDE_BIN,
54
		];
55
56
		return {
57
			data: data.join(''),
58
			text: this.text
59
		};
60
	}
61
62
}
63
64
export default EAN8;
65