Skip to content

Commit 5e22d48

Browse files
committed
Make file size more compact
1 parent 0de5602 commit 5e22d48

File tree

2 files changed

+10
-9
lines changed

2 files changed

+10
-9
lines changed

src/lib/helpers.ts

+6-5
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,23 @@ export function getFileContent(file: Buffer | string): string {
88
return buffer.toString();
99
}
1010

11-
const BYTE_SIZES = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
11+
const BYTE_SIZES = ['B', 'K', 'M', 'G', 'TB', 'PB', 'EB', 'ZB', 'YB'];
1212
// Bytes
1313
const SIZE_BASE = 1024;
1414

1515
/**
1616
* Format number of bytes as string
17-
* Source @see https://stackoverflow.com/a/18650828/388951
1817
*/
19-
export function formatBytes(bytes: number, decimals = 2): string {
20-
if (bytes === 0) return `0 ${BYTE_SIZES[0]}`;
18+
export function formatBytes(bytes: number, maximumSignificantDigits = 3): string {
19+
if (bytes === 0) return `0${BYTE_SIZES[0]}`;
2120

2221
const exponent = Math.floor(Math.log(bytes) / Math.log(SIZE_BASE));
2322
const value = bytes / Math.pow(SIZE_BASE, exponent);
2423

2524
// `parseFloat` removes trailing zero
26-
return `${parseFloat(value.toFixed(decimals))} ${BYTE_SIZES[exponent]}`;
25+
return `${new Intl.NumberFormat('default', { maximumSignificantDigits }).format(value)}${
26+
BYTE_SIZES[exponent]
27+
}`;
2728
}
2829

2930
export function formatPercent(value: number, total: number, fractionDigits?: number): string {

tests/unit/helpers.test.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ import type { MappingRange } from '../../src/lib/types';
1414
describe('helpers', () => {
1515
describe('formatBytes', () => {
1616
const tests: { bytes: number; expected: string }[] = [
17-
{ bytes: 0, expected: '0 B' },
18-
{ bytes: 1024, expected: '1 KB' },
19-
{ bytes: 27291, expected: '26.65 KB' },
20-
{ bytes: 6232294, expected: '5.94 MB' },
17+
{ bytes: 0, expected: '0B' },
18+
{ bytes: 1024, expected: '1K' },
19+
{ bytes: 27291, expected: '26.7K' },
20+
{ bytes: 6232294, expected: '5.94M' },
2121
];
2222

2323
tests.forEach(({ bytes, expected }) => {

0 commit comments

Comments
 (0)