Skip to content

Commit

Permalink
Make file size more compact
Browse files Browse the repository at this point in the history
  • Loading branch information
caub committed Mar 20, 2021
1 parent 0de5602 commit 5e22d48
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
11 changes: 6 additions & 5 deletions src/lib/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) => {
Expand Down

0 comments on commit 5e22d48

Please sign in to comment.