-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathutils.ts
99 lines (90 loc) · 2.54 KB
/
utils.ts
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
export function parseJson(value?: string | null) {
if (!value) {
return undefined;
}
try {
return JSON.parse(value);
} catch {
return value;
}
}
const sizes = [' B', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB'];
const base = 1000;
export function bytesToSize(bytes: number) {
if (isNaN(bytes)) {
return '';
}
if (bytes < base) {
return String(bytes);
}
let i = parseInt(String(Math.floor(Math.log(bytes) / Math.log(base))), 10);
if (i >= sizes.length) {
i = sizes.length - 1;
}
let val = bytes / Math.pow(base, i);
if (val > 999) {
val = val / base;
i++;
}
return val.toPrecision(3) + sizes[i];
}
function bytesToMB(bytes?: number | string) {
const bytesNumber = Number(bytes);
if (isNaN(bytesNumber)) {
return '';
}
const val = bytesNumber / base ** 2;
if (val < 10) {
return val.toFixed(2) + sizes[2];
} else if (val < 100) {
return val.toFixed(1) + sizes[2];
} else {
return val.toFixed() + sizes[2];
}
}
export function bytesToSpeed(bytes?: number | string) {
const speed = bytesToMB(bytes);
return `${speed}${speed ? 'ps' : ''}`;
}
export function bytesToGB(bytes?: number | string, shouldRound?: boolean) {
const bytesNumber = Number(bytes);
if (isNaN(bytesNumber)) {
return 'N/A';
}
const val = bytesNumber / 1000000000;
if (shouldRound) {
return val.toFixed() + sizes[3];
}
if (val < 10) {
return val.toFixed(2) + sizes[3];
} else if (val < 100) {
return val.toFixed(1) + sizes[3];
} else {
return val.toFixed() + sizes[3];
}
}
export function pad9(val: number | string) {
const stringifiedVal = String(val);
const len = stringifiedVal.length;
let result = stringifiedVal;
for (let i = len; i < 9; i++) {
result = '0' + result;
}
return result;
}
export function isNumeric(value?: unknown): value is number | string {
if (typeof value === 'number') {
return !isNaN(value);
}
if (typeof value === 'string') {
// need both isNaN and isNaN(parseFloat):
// - isNaN treats true/false/''/etc. as numbers, parseFloat fixes this
// - parseFloat treats '123qwe' as number, isNaN fixes this
return !isNaN(Number(value)) && !isNaN(parseFloat(value));
}
return false;
}
export function toExponential(value: number, precision?: number) {
return Number(value).toExponential(precision);
}
export const UNBREAKABLE_GAP = '\xa0';