Skip to content

Commit 00abdc0

Browse files
authored
Merge pull request #313 from crazy-max/util-format-size
util: formatFileSize
2 parents 0f39343 + 7621606 commit 00abdc0

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

__tests__/util.test.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,32 @@ describe('parseBool', () => {
309309
});
310310
});
311311

312+
describe('formatFileSize', () => {
313+
test('should return "0 Bytes" when given 0 bytes', () => {
314+
expect(Util.formatFileSize(0)).toBe('0 Bytes');
315+
});
316+
test('should format bytes to KB correctly', () => {
317+
expect(Util.formatFileSize(1024)).toBe('1 KB');
318+
expect(Util.formatFileSize(2048)).toBe('2 KB');
319+
expect(Util.formatFileSize(1500)).toBe('1.46 KB');
320+
});
321+
test('should format bytes to MB correctly', () => {
322+
expect(Util.formatFileSize(1024 * 1024)).toBe('1 MB');
323+
expect(Util.formatFileSize(2.5 * 1024 * 1024)).toBe('2.5 MB');
324+
expect(Util.formatFileSize(3.8 * 1024 * 1024)).toBe('3.8 MB');
325+
});
326+
test('should format bytes to GB correctly', () => {
327+
expect(Util.formatFileSize(1024 * 1024 * 1024)).toBe('1 GB');
328+
expect(Util.formatFileSize(2.5 * 1024 * 1024 * 1024)).toBe('2.5 GB');
329+
expect(Util.formatFileSize(3.8 * 1024 * 1024 * 1024)).toBe('3.8 GB');
330+
});
331+
test('should format bytes to TB correctly', () => {
332+
expect(Util.formatFileSize(1024 * 1024 * 1024 * 1024)).toBe('1 TB');
333+
expect(Util.formatFileSize(2.5 * 1024 * 1024 * 1024 * 1024)).toBe('2.5 TB');
334+
expect(Util.formatFileSize(3.8 * 1024 * 1024 * 1024 * 1024)).toBe('3.8 TB');
335+
});
336+
});
337+
312338
// See: https://github.com/actions/toolkit/blob/a1b068ec31a042ff1e10a522d8fdf0b8869d53ca/packages/core/src/core.ts#L89
313339
function getInputName(name: string): string {
314340
return `INPUT_${name.replace(/ /g, '_').toUpperCase()}`;

src/util.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,4 +166,12 @@ export class Util {
166166
throw new Error(`parseBool syntax error: ${str}`);
167167
}
168168
}
169+
170+
public static formatFileSize(bytes: number): string {
171+
if (bytes === 0) return '0 Bytes';
172+
const k = 1024;
173+
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
174+
const i = Math.floor(Math.log(bytes) / Math.log(k));
175+
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
176+
}
169177
}

0 commit comments

Comments
 (0)