-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathformatBytes.ts
93 lines (76 loc) · 2.13 KB
/
formatBytes.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
import {GIGABYTE, KILOBYTE, MEGABYTE, TERABYTE} from '../constants';
import type {FormatToSizeArgs, FormatValuesArgs} from '../dataFormatters/common';
import {formatNumber, roundToPrecision} from '../dataFormatters/dataFormatters';
import {UNBREAKABLE_GAP, isNumeric} from '../utils';
import i18n from './i18n';
const sizes = {
b: {
value: 1,
label: i18n('b'),
},
kb: {
value: KILOBYTE,
label: i18n('kb'),
},
mb: {
value: MEGABYTE,
label: i18n('mb'),
},
gb: {
value: GIGABYTE,
label: i18n('gb'),
},
tb: {
value: TERABYTE,
label: i18n('tb'),
},
} as const;
export type BytesSizes = keyof typeof sizes;
export const getBytesSizeUnit = (value: number) => {
let size: BytesSizes = 'b';
if (value >= sizes.kb.value) {
size = 'kb';
}
if (value >= sizes.mb.value) {
size = 'mb';
}
if (value >= sizes.gb.value) {
size = 'gb';
}
if (value >= sizes.tb.value) {
size = 'tb';
}
return size;
};
const formatToSize = ({value, size = 'mb', precision = 0}: FormatToSizeArgs<BytesSizes>) => {
const result = roundToPrecision(Number(value) / sizes[size].value, precision);
return formatNumber(result);
};
const addSizeLabel = (result: string, size: BytesSizes, delimiter = UNBREAKABLE_GAP) => {
return result + delimiter + sizes[size].label;
};
const addSpeedLabel = (result: string, size: BytesSizes) => {
return addSizeLabel(result, size) + i18n('perSecond');
};
export const formatBytes = ({
value,
size,
withSpeedLabel = false,
withSizeLabel = true,
delimiter,
...params
}: FormatValuesArgs<BytesSizes>) => {
if (!isNumeric(value)) {
return '';
}
const numValue = Number(value);
const sizeToConvert = size ?? getBytesSizeUnit(numValue);
const result = formatToSize({value: numValue, size: sizeToConvert, ...params});
if (withSpeedLabel) {
return addSpeedLabel(result, sizeToConvert);
}
if (withSizeLabel) {
return addSizeLabel(result, sizeToConvert, delimiter);
}
return result;
};