Created
February 14, 2025 23:32
-
-
Save diegovgsilva95/5297458a4199f5b538ea9b7c2f2caa5a to your computer and use it in GitHub Desktop.
JS - Humanize and dehumanize byte-unit inputs (with support for both SI and binary byte prefixes)
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
| // Note: I'm ignoring fractional bytes (e.g., 4.2 B is invalid input; 4.2 KiB or 4.2 KB are valid, tho ). | |
| export const humanizeBytes = function(bytes, si = false, digits = 1){ | |
| let basis = si ? 1000 : 1024 | |
| let scale = (Math.log(Math.max(1,bytes)) / Math.log(basis))|0 | |
| let coeff = bytes / (basis ** scale) | |
| let unit = scale == 0 ? "B" : ("KMGTP"[scale-1] + (si ? "" : "i") + "B") | |
| return `${coeff.toFixed(scale == 0 ? 0 : digits)} ${unit}` | |
| } | |
| export const dehumanizeBytes = function(humanText){ | |
| let matched = humanText.match(/^([0-9]+) ?(B|K|KB|KiB|M|MB|MiB|G|GB|GiB|T|TB|TiB|P|PB|PiB)?$/) | |
| || humanText.match(/^([0-9]+\.[0-9]+) ?(K|KB|KiB|M|MB|MiB|G|GB|GiB|T|TB|TiB|P|PB|PiB)$/) | |
| if(!matched) | |
| return null | |
| let [coeff, scale] = matched.slice(1, 3) | |
| coeff = parseFloat(coeff)||0 | |
| scale = typeof scale === "undefined" ? 1 : (scale.length>2 ? 1024 : 1000) ** ("KMGTP".indexOf(scale[0])+1) | |
| return Math.trunc(coeff * scale) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In order to better support Petabytes/Pebibytes, you should adapt it to "BigNumber"/"BigInt" (be it the JS native or third-party libraries), because such scale isn't well-represented by IEEE 754.
Also, in order to support higher scales (such as Yottabytes/Yobibytes... but I wonder what exactly are you planning to do with such large scales), add them to the RegExps, as well as to the hardcoded string (but I guess you already know it, given you're dealing with daunting Yottabytes of data... who are you working for, a multinational ISP provider? Perhaps a Big Tech employee? Help hiring me?).