From 5e22d48d7547837964460100b092b8e408f62b78 Mon Sep 17 00:00:00 2001 From: caub Date: Sat, 20 Mar 2021 14:16:49 +0100 Subject: [PATCH] Make file size more compact --- src/lib/helpers.ts | 11 ++++++----- tests/unit/helpers.test.ts | 8 ++++---- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/lib/helpers.ts b/src/lib/helpers.ts index 5cc459a..5037545 100644 --- a/src/lib/helpers.ts +++ b/src/lib/helpers.ts @@ -8,22 +8,23 @@ export function getFileContent(file: Buffer | string): string { return buffer.toString(); } -const BYTE_SIZES = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; +const BYTE_SIZES = ['B', 'K', 'M', 'G', 'TB', 'PB', 'EB', 'ZB', 'YB']; // Bytes const SIZE_BASE = 1024; /** * Format number of bytes as string - * Source @see https://stackoverflow.com/a/18650828/388951 */ -export function formatBytes(bytes: number, decimals = 2): string { - if (bytes === 0) return `0 ${BYTE_SIZES[0]}`; +export function formatBytes(bytes: number, maximumSignificantDigits = 3): string { + if (bytes === 0) return `0${BYTE_SIZES[0]}`; const exponent = Math.floor(Math.log(bytes) / Math.log(SIZE_BASE)); const value = bytes / Math.pow(SIZE_BASE, exponent); // `parseFloat` removes trailing zero - return `${parseFloat(value.toFixed(decimals))} ${BYTE_SIZES[exponent]}`; + return `${new Intl.NumberFormat('default', { maximumSignificantDigits }).format(value)}${ + BYTE_SIZES[exponent] + }`; } export function formatPercent(value: number, total: number, fractionDigits?: number): string { diff --git a/tests/unit/helpers.test.ts b/tests/unit/helpers.test.ts index 7767c41..53fcc02 100644 --- a/tests/unit/helpers.test.ts +++ b/tests/unit/helpers.test.ts @@ -14,10 +14,10 @@ import type { MappingRange } from '../../src/lib/types'; describe('helpers', () => { describe('formatBytes', () => { const tests: { bytes: number; expected: string }[] = [ - { bytes: 0, expected: '0 B' }, - { bytes: 1024, expected: '1 KB' }, - { bytes: 27291, expected: '26.65 KB' }, - { bytes: 6232294, expected: '5.94 MB' }, + { bytes: 0, expected: '0B' }, + { bytes: 1024, expected: '1K' }, + { bytes: 27291, expected: '26.7K' }, + { bytes: 6232294, expected: '5.94M' }, ]; tests.forEach(({ bytes, expected }) => {