-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathValueParser.js
96 lines (86 loc) · 3.1 KB
/
ValueParser.js
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
'use strict';
const decimals = function (value, x, base) {
var pow = Math.pow(base || 10, x);
return Math.round(value * pow) / pow;
};
const formatValue = function (value, capability, percentageScale) {
if (typeof value === 'boolean') {
return value ? 'true' : 'false';
}
if (capability && percentageScale && capability.units === '%') {
switch (percentageScale) {
case 'int':
if (capability.min === 0 && capability.max === 1)
return value * 100;
break;
case 'float':
if (capability.min === 0 && capability.max === 100)
return value / 100;
break;
case 'default':
default:
// nothing
break;
}
}
return value;
};
const parseValue = function (value, capability, percentageScale) {
if (capability) {
// Handle percentage scaling
if (percentageScale && capability.units === '%') {
switch (percentageScale) {
case 'int':
if (capability.min === 0 && capability.max === 1)
return parseValue(value, 'integer') / 100.0;
break;
case 'float':
if (capability.min === 0 && capability.max === 100)
return round(parseValue(value, 'float') * 100, 0, 100);
break;
case 'default':
default:
// nothing
break;
}
}
// by data type
switch (capability.type) {
case 'boolean':
if (typeof value === 'string') {
value = value.replace(/\'/gi,'').toLowerCase();
}
return value === true || value === 'true' || value === 1 || value === '1' || value === 'on' || value === 'yes';
case 'number':
case 'float':
value = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) || 0 : 0;
return capability.decimals >= 0 ? decimals(value, capability.decimals) : value;
case 'integer':
return typeof value === 'number' ? value : typeof value === 'string' ? parseInt(value) || 0 : 0;
case 'string':
return value ? value.toString() : undefined;
case 'enum':
case 'color':
default:
break;
}
}
switch (typeof value) {
case 'boolean':
case 'number':
return value;
default:
let numeric = Number(value);
return isNaN(numeric) ? value : numeric;
}
};
const formatOnOff = function (value, onOffValues) {
switch (onOffValues) {
case 'bool': return value ? 'true' : 'false';
case 'int': return value ? '1' : '0';
case 'onoff': return value ? 'on' : 'off';
case 'yesno': return value ? 'yes' : 'no';
}
return value;
};
module.exports = { decimals, formatValue, parseValue, formatOnOff };