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 = { 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'; } }