-
-
Save luislobo14rap/b0368c1ed36a809bac667d8301152baa to your computer and use it in GitHub Desktop.
to-file-size.js
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
| // to-file-size.js v1 | |
| function toFileSize(sizeInBytes, abbreviation = true, decimalPlaces = 2, removeDecimalZeros = true, plural) { | |
| if (typeof sizeInBytes !== "number" || sizeInBytes < 0 || !Number.isFinite(sizeInBytes)) { | |
| throw new Error("Invalid input: sizeInBytes must be a non-negative finite number.") | |
| } | |
| if (sizeInBytes === 0) { | |
| return !abbreviation ? "0 Bytes" : "0 bytes" | |
| } | |
| if (plural === undefined) { | |
| plural = !abbreviation ? true : false | |
| } | |
| const units = abbreviation ? | |
| ["Byte", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "BB", "NB", "DB", "CB"] : | |
| ["byte", "kilobyte", "megabyte", "gigabyte", "terabyte", "petabyte", "exabyte", "zettabyte", "yottabyte", "brontobyte", "ninettabyte", "decobyte", "centobyte"] | |
| const exponent = Math.floor(Math.log(sizeInBytes) / Math.log(1024)), | |
| size = sizeInBytes / Math.pow(1024, exponent) | |
| let formattedSize = size.toFixed(decimalPlaces), | |
| unit = "" | |
| if (removeDecimalZeros && /\.0+/.test(formattedSize)) { | |
| formattedSize = formattedSize.split(".")[0] | |
| } | |
| if (units[exponent]) { | |
| unit = units[exponent] + (plural ? "s" : "") | |
| } else { | |
| unit = "Unknown" | |
| } | |
| if (plural && /^(1|1\.0+)$/.test(formattedSize)) { | |
| unit = unit.replace(/s$/, "") | |
| } | |
| return formattedSize + " " + unit | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
antes de usar comparar com:
https://www.npmjs.com/package/bytes
https://github.com/sindresorhus/pretty-bytes