Created
April 5, 2024 18:14
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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