Files
zero-fucks-given/packages/utils/src/formaters/bytesToHumanReadableFormat.ts
T

13 lines
423 B
TypeScript
Executable File

const thresh = 1024;
export function bytesToHumanReadableFormat(bytes: number, units: string[] = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']): string {
let bytesCopy = bytes;
if (bytesCopy < thresh) return `${bytesCopy} ${units[0]}`;
let u = -1;
do {
bytesCopy /= thresh;
++u;
} while (bytesCopy >= thresh && u + 1 < units.length - 1);
return `${bytesCopy.toFixed(1)} ${units[u + 1]}`;
}