From 941dc3700ecc717c9a998661f05d972bcf34cf32 Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Mon, 8 Nov 2021 00:25:28 +0100 Subject: [PATCH] Add FileSize helper class --- src/common/FileSize.ts | 48 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/common/FileSize.ts diff --git a/src/common/FileSize.ts b/src/common/FileSize.ts new file mode 100644 index 0000000..6ea0036 --- /dev/null +++ b/src/common/FileSize.ts @@ -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 = { + 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'; + } +}