aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/root-helpers/bytes.ts
blob: 7b1920a090cae30c6f6ac8640d04ee796286d842 (plain) (blame)
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
const dictionary: { max: number, type: string }[] = [
  { max: 1024, type: 'B' },
  { max: 1048576, type: 'KB' },
  { max: 1073741824, type: 'MB' },
  { max: 1.0995116e12, type: 'GB' }
]

function getBytes (value: number, precision?: number | undefined): string | number {
  const format = dictionary.find(d => value < d.max) || dictionary[dictionary.length - 1]
  const calc = value / (format.max / 1024)

  const num = precision === undefined
    ? calc
    : applyPrecision(calc, precision)

  return `${num} ${format.type}`
}

function applyPrecision (num: number, precision: number) {
  if (precision <= 0) {
    return Math.round(num)
  }

  const tho = 10 ** precision

  return Math.round(num * tho) / tho
}

export {
  getBytes
}