2021-08-17 07:42:53 -05:00
|
|
|
const dictionary: Array<{ max: number, type: string }> = [
|
2020-08-14 10:28:54 -05:00
|
|
|
{ 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
|
|
|
|
}
|