1 | const ONE_SECOND_AS_MS = 1000;
|
2 | const ONE_MINUTE_AS_MS = 60 * ONE_SECOND_AS_MS;
|
3 | const ONE_HOUR_AS_MS = 60 * ONE_MINUTE_AS_MS;
|
4 |
|
5 | export function formatMS(
|
6 | ms: number,
|
7 | d: number,
|
8 | allowMicros = false,
|
9 | allowNanos = true
|
10 | ) {
|
11 | if (ms === 0 || ms === null) return "0";
|
12 | const bounds = [
|
13 | ONE_HOUR_AS_MS,
|
14 | ONE_MINUTE_AS_MS,
|
15 | ONE_SECOND_AS_MS,
|
16 | 1,
|
17 | 0.001,
|
18 | 0.000001,
|
19 | ];
|
20 | const units = ["hr", "min", "s", "ms", "μs", "ns"];
|
21 |
|
22 | const makeSmallNumbersNice = (f: number) => {
|
23 | if (f >= 100) return f.toFixed(0);
|
24 | if (f >= 10) return f.toFixed(1);
|
25 | if (f === 0) return "0";
|
26 | return f.toFixed(2);
|
27 | };
|
28 |
|
29 | const bound = bounds.find((b) => b <= ms) || bounds[bounds.length - 1];
|
30 | const boundIndex = bounds.indexOf(bound);
|
31 | const unit = boundIndex >= 0 ? units[boundIndex] : "";
|
32 |
|
33 | if ((unit === "μs" || unit === "ns") && !allowMicros) {
|
34 | return "< 1ms";
|
35 | }
|
36 | if (unit === "ns" && !allowNanos) {
|
37 | return "< 1µs";
|
38 | }
|
39 | const value =
|
40 | typeof d !== "undefined"
|
41 | ? (ms / bound).toFixed(d)
|
42 | : makeSmallNumbersNice(ms / bound);
|
43 |
|
44 |
|
45 | if ((value === "1000" || value === "1000.0") && boundIndex >= 1) {
|
46 | return `1${units[boundIndex - 1]}`;
|
47 | }
|
48 |
|
49 | return `${value}${unit}`;
|
50 | }
|