Skip to content

Instantly share code, notes, and snippets.

@ntorga
Created April 5, 2024 18:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntorga/d80258d6c45eeebdcc1f62447b769366 to your computer and use it in GitHub Desktop.
Save ntorga/d80258d6c45eeebdcc1f62447b769366 to your computer and use it in GitHub Desktop.
A human readable bytes adapter for TypeScript/JavaScript that is actually (and finally) readable.
function humanReadableBytesAdapter(rawBytesQuantity: number): string {
const bytesUnits = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
let unitSuffixIndex = 0;
const isQuantityNegative = rawBytesQuantity < 0;
const rawBytesQuantityAbsolute = Math.abs(rawBytesQuantity);
let shortestBytesNumeral = rawBytesQuantityAbsolute;
while (shortestBytesNumeral >= 1024 && unitSuffixIndex < bytesUnits.length - 1) {
shortestBytesNumeral /= 1024;
unitSuffixIndex++;
}
let shortestBytesNumeralString = shortestBytesNumeral.toFixed(2);
if (isQuantityNegative) {
shortestBytesNumeralString = "-" + shortestBytesNumeralString;
}
return `${shortestBytesNumeralString} ${bytesUnits[unitSuffixIndex]}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment