Skip to content

Commit

Permalink
Merge pull request #313 from crazy-max/util-format-size
Browse files Browse the repository at this point in the history
util: formatFileSize
  • Loading branch information
crazy-max committed Apr 25, 2024
2 parents 0f39343 + 7621606 commit 00abdc0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
26 changes: 26 additions & 0 deletions __tests__/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,32 @@ describe('parseBool', () => {
});
});

describe('formatFileSize', () => {
test('should return "0 Bytes" when given 0 bytes', () => {
expect(Util.formatFileSize(0)).toBe('0 Bytes');
});
test('should format bytes to KB correctly', () => {
expect(Util.formatFileSize(1024)).toBe('1 KB');
expect(Util.formatFileSize(2048)).toBe('2 KB');
expect(Util.formatFileSize(1500)).toBe('1.46 KB');
});
test('should format bytes to MB correctly', () => {
expect(Util.formatFileSize(1024 * 1024)).toBe('1 MB');
expect(Util.formatFileSize(2.5 * 1024 * 1024)).toBe('2.5 MB');
expect(Util.formatFileSize(3.8 * 1024 * 1024)).toBe('3.8 MB');
});
test('should format bytes to GB correctly', () => {
expect(Util.formatFileSize(1024 * 1024 * 1024)).toBe('1 GB');
expect(Util.formatFileSize(2.5 * 1024 * 1024 * 1024)).toBe('2.5 GB');
expect(Util.formatFileSize(3.8 * 1024 * 1024 * 1024)).toBe('3.8 GB');
});
test('should format bytes to TB correctly', () => {
expect(Util.formatFileSize(1024 * 1024 * 1024 * 1024)).toBe('1 TB');
expect(Util.formatFileSize(2.5 * 1024 * 1024 * 1024 * 1024)).toBe('2.5 TB');
expect(Util.formatFileSize(3.8 * 1024 * 1024 * 1024 * 1024)).toBe('3.8 TB');
});
});

// See: https://github.com/actions/toolkit/blob/a1b068ec31a042ff1e10a522d8fdf0b8869d53ca/packages/core/src/core.ts#L89
function getInputName(name: string): string {
return `INPUT_${name.replace(/ /g, '_').toUpperCase()}`;
Expand Down
8 changes: 8 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,4 +166,12 @@ export class Util {
throw new Error(`parseBool syntax error: ${str}`);
}
}

public static formatFileSize(bytes: number): string {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
}

0 comments on commit 00abdc0

Please sign in to comment.