Source code

Revision control

Copy as Markdown

Other Tools

/*
Author Sean Larkin @thelarkinn
*/
"use strict";
/**
* Returns the formatted size.
* @param {number=} size the size in bytes
* @returns {string} the formatted size
*/
const formatSize = (size) => {
if (typeof size !== "number" || Number.isNaN(size) === true) {
return "unknown size";
}
if (size <= 0) {
return "0 bytes";
}
const abbreviations = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB"];
// clamp so sizes beyond the largest unit don't index past the table
const index = Math.min(
Math.floor(Math.log(size) / Math.log(1024)),
abbreviations.length - 1
);
return `${Number((size / 1024 ** index).toPrecision(3))} ${abbreviations[index]}`;
};
module.exports = formatSize;