-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBarcodeFunctions.gs
98 lines (79 loc) · 1.93 KB
/
BarcodeFunctions.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// vim: set ft=javascript:
/**
* Calculates the check digit for barcode.
*
* @param {"0123456789"} barcode A barcode without a check digit.
* @return {String} The check digit for barcode.
* @customfunction
*/
function CALC_CHECK_DIGIT(barcode) {
if (barcode.map) {
return barcode.map(CALC_CHECK_DIGIT);
}
var digits = barcode.split('');
var odds = 0;
var evens = 0;
for (var i=digits.length - 1; i >= 0; i--) {
var num = +digits[i];
if ( i % 2 === 0 ) {
odds += num;
} else {
evens += num;
}
}
return (10 - (odds * 3 + evens) % 10) % 10;
}
/**
* Returns whether the check digit for barcode is valid.
*
* @param {"012345678905"} barcode A barcode with a check digit.
* @return {Boolean} TRUE or FALSE if valid or invalid.
* @customfunction
*/
function VALID_CHECK_DIGIT(barcode) {
if (barcode.map) {
return barcode.map(VALID_CHECK_DIGIT);
}
return CALC_CHECK_DIGIT(barcode.slice(0, -1)) === +barcode.slice(-1);
}
/**
* Calculates and appends a check digit for digits.
*
* @param {"01234567890"} digits A barcode without a check digit.
* @return {String} The full barcode with the calculated check digit appended.
* @customfunction
*/
function APPEND_CHECK_DIGIT(digits) {
if (digits.map) {
return digits.map(APPEND_CHECK_DIGIT);
}
return digits + CALC_CHECK_DIGIT(digits);
}
var BarcodeTypes = {
12: "UPC-A",
13: "GTIN-13",
14: "GTIN-14"
}
/**
* Returns the barcode type based on length.
* @param {"012345678905"} barcode A barcode.
* @return {String} The barcode type.
* @customfunction
*/
function BARCODE_TYPE(barcode) {
if (barcode.map) {
return barcode.map(BARCODE_TYPE);
}
if (!VALID_CHECK_DIGIT(barcode)) {
throw new Error(
barcode + " has an invalid check digit."
);
}
var type = BarcodeTypes[barcode.length];
if (type) {
return type;
}
throw new Error(
barcode.length + " is not a valid barcode size."
);
}