]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/root-helpers/bytes.ts
Merge branch 'release/4.3.0' into develop
[github/Chocobozzz/PeerTube.git] / client / src / root-helpers / bytes.ts
CommitLineData
9df52d66 1const dictionary: Array<{ max: number, type: string }> = [
b4c3c51d
C
2 { max: 1024, type: 'B' },
3 { max: 1048576, type: 'KB' },
4 { max: 1073741824, type: 'MB' },
5 { max: 1.0995116e12, type: 'GB' }
6]
7
8function getBytes (value: number, precision?: number | undefined): string | number {
9 const format = dictionary.find(d => value < d.max) || dictionary[dictionary.length - 1]
10 const calc = value / (format.max / 1024)
11
12 const num = precision === undefined
13 ? calc
14 : applyPrecision(calc, precision)
15
16 return `${num} ${format.type}`
17}
18
19function applyPrecision (num: number, precision: number) {
20 if (precision <= 0) {
21 return Math.round(num)
22 }
23
24 const tho = 10 ** precision
25
26 return Math.round(num * tho) / tho
27}
28
29export {
30 getBytes
31}