All files / cli / _unit.ts

100.00% Branches 4/4
100.00% Lines 24/24
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
 
 
 
 
 
 
 
 
 
 
 
 
x6
x24
x24
x24
x24
x24
x24
x24
x18
x6
 
x59
x236
x59
x177
x349
x349
x59
x59
 
x6
x59
x59
x59
x59
x59




































// Copyright 2018-2025 the Deno authors. MIT license.

type Unit =
  | "KiB"
  | "MiB"
  | "GiB"
  | "TiB"
  | "PiB"
  | "EiB"
  | "ZiB"
  | "YiB";

const UNIT_RATE_MAP = new Map<Unit, number>([
  ["KiB", 2 ** 10],
  ["MiB", 2 ** 20],
  ["GiB", 2 ** 30],
  ["TiB", 2 ** 40],
  ["PiB", 2 ** 50],
  ["EiB", 2 ** 60],
  ["ZiB", 2 ** 70],
  ["YiB", 2 ** 80],
]);

function getUnitEntry(max: number): [Unit, number] {
  let result: [Unit, number] = ["KiB", 2 ** 10];
  for (const entry of UNIT_RATE_MAP) {
    if (entry[1] > max) break;
    result = entry;
  }
  return result;
}

export function formatUnitFraction(value: number, max: number) {
  const [unit, rate] = getUnitEntry(max);
  const currentValue = (value / rate).toFixed(2);
  const maxValue = (max / rate).toFixed(2);
  return `${currentValue}/${maxValue} ${unit}`;
}