Add FileSize helper class

This commit is contained in:
Alice Gaudon 2021-11-08 00:25:28 +01:00
parent 4a8a1f2da8
commit 941dc3700e

48
src/common/FileSize.ts Normal file
View File

@ -0,0 +1,48 @@
export class FileSizeUnit {
public constructor(
public readonly bytes: number,
public readonly longName: string,
public readonly shortName: string,
public readonly divisible: boolean = true,
) {
}
}
export class FileSize {
public static readonly UNITS: Record<string, FileSizeUnit> = {
B: new FileSizeUnit(1, 'byte', 'B', false),
KB: new FileSizeUnit(1000, 'kilobyte', 'kB'),
MB: new FileSizeUnit(1000 * 1000, 'megabyte', 'MB'),
GB: new FileSizeUnit(1000 * 1000 * 1000, 'gigabyte', 'GB'),
TB: new FileSizeUnit(1000 * 1000 * 1000 * 1000, 'terabyte', 'TB'),
};
public static humanizeFileSize(
size: number,
short: boolean = false,
skipOneUnitNumber: boolean = false,
units: FileSizeUnit[] = [
this.UNITS.B,
this.UNITS.KB,
this.UNITS.MB,
this.UNITS.GB,
this.UNITS.TB,
],
): string {
for (let i = units.length - 1; i > 0; i--) {
const fileSizeUnit = units[i - 1];
if (size >= fileSizeUnit.bytes && size < units[i].bytes) {
const amount = size / fileSizeUnit.bytes;
const unit = short ?
fileSizeUnit.shortName :
' ' + fileSizeUnit.longName + (amount > 1 ? 's' : '');
const strAmount = fileSizeUnit.divisible ?
amount.toFixed(1) :
Math.floor(amount);
return (amount > 1 || !skipOneUnitNumber ? strAmount : '') + unit;
}
}
return '0';
}
}