-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutilities.js
114 lines (97 loc) · 2.63 KB
/
utilities.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
'use strict';
require('dotenv').config();
// const config = require('./config');
const math = require('@dip1059/safe-math-js');
// const { TEST, LOG_TIME, LOG_API_CALL_TIME } = process.env;
const { LOG_API_CALL_TIME } = process.env;
const measureTime = (start, format = true) => {
if (!LOG_API_CALL_TIME) return null;
// const NS_PER_SEC = 1e9;
const NUM_IN_MS = 1000000;
if (start) {
const diff = process.hrtime(start);
const time = format ?
(diff[0] ? diff[0] + ' sec, ' : '') +
(diff[1] / NUM_IN_MS).toFixed(3) +
'ms' :
parseFloat(diff[0] * 1000 + (diff[1] / NUM_IN_MS).toFixed(3));
return time;
}
return process.hrtime();
};
// const formatMilliseconds = (milliseconds) => {
// const ms = milliseconds % 1000;
// milliseconds = (milliseconds - ms) / 1000;
// }
const delay = (time) =>
new Promise((resolve) => {
setTimeout(resolve, time);
});
const random = (min, max) => Math.round(Math.random() * (max - min) + min);
const roughSizeOfObject = (value) => {
const typeSizes = {
undefined: () => 0,
boolean: () => 4,
number: () => 8,
bigint: () => 8,
string: (item) => 2 * item.length,
object: (item) =>
(!item ?
0 :
Object.keys(item).reduce(
(total, key) =>
roughSizeOfObject(key) +
roughSizeOfObject(item[key]) +
total,
0,
)),
};
return typeSizes[typeof value](value);
};
const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
const humanFileSize = (bytes, si = false, dp = 1) => {
const thresh = si ? 1000 : 1024;
if (Math.abs(bytes) < thresh) {
return bytes + ' B';
}
const units = si ?
['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] :
['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
let u = -1;
const r = 10 ** dp;
do {
bytes /= thresh;
++u;
} while (
Math.round(Math.abs(bytes) * r) / r >= thresh &&
u < units.length - 1
);
return bytes.toFixed(dp) + ' ' + units[u];
};
const safeRequire = (modulePath) => {
try {
return require(modulePath);
} catch {
console.log(
'safeRequire(): The file "' + modulePath + '".js could not be loaded.',
);
return false;
}
};
module.exports = {
measureTime,
math,
delay,
random,
roughSizeOfObject,
formatBytes,
humanFileSize,
safeRequire,
};