This commit is contained in:
Brett Gilio 2024-04-25 09:18:35 +08:00 committed by GitHub
commit b3d057a6f1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,8 +1,15 @@
const sizes = ["Bytes", "KiB", "MiB", "GiB", "TiB", "PiB"]; const sizes = ["Bytes", "KiB", "MiB", "GiB", "TiB", "PiB"];
export default (size: number) => { export default function formatSize(size: number): string {
// Loosely inspired from https://stackoverflow.com/a/18650828/1935861 if (size <= 0) {
const i = size > 0 ? Math.floor(Math.log(size) / Math.log(1024)) : 0; throw new Error("Size must be a positive number");
const fixedSize = parseFloat((size / Math.pow(1024, i)).toFixed(1)); }
return `${fixedSize} ${sizes[i]}`;
}; const i = Math.floor(Math.log(size) / Math.log(1024));
if (i >= sizes.length) {
throw new Error("Size is out of range");
}
return `${(size / Math.pow(1024, i)).toFixed(1)} ${sizes[i]}`;
}