Completed
Pull Request — master (#99)
by Johan
01:15
created

src/barcodes/ITF14/index.js   A

Size

Lines of Code 74

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
nc 1
dl 0
loc 74
rs 10
c 0
b 0
f 0
noi 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A index.js ➔ ??? 0 21 2
1
class ITF14{
2
	constructor(string){
3
		this.string = string;
4
5
		// Add checksum if it does not exist
6
		if(string.search(/^[0-9]{13}$/) !== -1){
7
			this.string += this.checksum(string);
8
		}
9
10
		this.binaryRepresentation = {
11
			"0":"00110",
12
			"1":"10001",
13
			"2":"01001",
14
			"3":"11000",
15
			"4":"00101",
16
			"5":"10100",
17
			"6":"01100",
18
			"7":"00011",
19
			"8":"10010",
20
			"9":"01010"
21
		};
22
	}
23
24
	valid(){
25
		return this.string.search(/^[0-9]{14}$/) !== -1 &&
26
			this.string[13] == this.checksum();
27
	}
28
29
	encode(){
30
		var result = "1010";
31
32
		// Calculate all the digit pairs
33
		for(var i = 0; i < 14; i += 2){
34
			result += this.calculatePair(this.string.substr(i, 2));
35
		}
36
37
		// Always add the same end bits
38
		result += "11101";
39
40
		return {
41
			data: result,
42
			text: this.string
43
		};
44
	}
45
46
	// Calculate the data of a number pair
47
	calculatePair(numberPair){
48
		var result = "";
49
50
		var number1Struct = this.binaryRepresentation[numberPair[0]];
51
		var number2Struct = this.binaryRepresentation[numberPair[1]];
52
53
		// Take every second bit and add to the result
54
		for(var i = 0; i < 5; i++){
55
			result += (number1Struct[i] == "1") ? "111" : "1";
56
			result += (number2Struct[i] == "1") ? "000" : "0";
57
		}
58
59
		return result;
60
	}
61
62
	// Calulate the checksum digit
63
	checksum(){
64
		var result = 0;
65
66
		for(var i = 0; i < 13; i++){
67
			result += parseInt(this.string[i]) * (3 - (i % 2) * 2);
68
		}
69
70
		return Math.ceil(result / 10) * 10 - result;
71
	}
72
}
73
74
export {ITF14};
75