-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
99 lines (75 loc) · 2.53 KB
/
main.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
97
98
99
const typeCheck = (variable) => {
if (typeof variable === 'string') return 'string';
if (typeof variable === 'number') return 'number';
if (typeof variable === 'object'
&& variable == null) return 'null';
if (typeof variable === 'object'
&& Array.isArray(variable)) return 'array';
if (typeof variable === 'object'
&& Buffer.isBuffer(variable)) return 'binary';
if (typeof variable === 'object') return 'object';
if (typeof variable === 'boolean') return 'boolean';
return false;
};
exports.typeCheck = typeCheck;
const calculateStringSize = value => value.length;
const calculateKeySize = key => key.length;
const calculateBinarySize = value => value.length;
const calculateNumberSize = (number) => {
if (!(typeof number === 'number')) return false;
let value = number;
value = value.toString();
value = value.replace('.', '');
return (Math.round(value.length / 2) + 1);
};
const calculateBooleanSize = () => 1;
const calculateNullSize = () => 1;
let calculateByType;
const calculateObjectSize = (object) => {
let totalSize = 3;
const keys = Object.keys(object);
const values = Object.values(object);
const numKeys = keys.length;
for (let index = 0; index < numKeys; index += 1) {
totalSize += (keys[index].length + calculateByType(values[index]));
}
return totalSize;
};
const calculateArraySize = (items) => {
let totalSize = 3;
items.forEach((element) => {
totalSize += calculateByType(element);
});
return totalSize;
};
calculateByType = (variable) => {
const type = typeCheck(variable);
switch (type) {
case 'string':
return calculateStringSize(variable);
case 'number':
return calculateNumberSize(variable);
case 'boolean':
return calculateBooleanSize();
case 'null':
return calculateNullSize();
case 'array':
return calculateArraySize(variable);
case 'object':
return calculateObjectSize(variable);
case 'binary':
return calculateBinarySize(variable);
default:
return false;
}
};
exports.calculateStringSize = calculateStringSize;
exports.calculateNumberSize = calculateNumberSize;
exports.calculateKeySize = calculateKeySize;
exports.calculateBooleanSize = calculateBooleanSize;
exports.calculateNullSize = calculateNullSize;
exports.calculateObjectSize = calculateObjectSize;
exports.calculateArraySize = calculateArraySize;
exports.calculateBinarySize = calculateBinarySize;
const calculateItemSize = item => calculateObjectSize(item) - 3;
exports.calculateItemSize = calculateItemSize;