Skip to content

Instantly share code, notes, and snippets.

@luislobo14rap
Created December 23, 2024 01:10
Show Gist options
  • Save luislobo14rap/b0368c1ed36a809bac667d8301152baa to your computer and use it in GitHub Desktop.
Save luislobo14rap/b0368c1ed36a809bac667d8301152baa to your computer and use it in GitHub Desktop.
to-file-size.js
// 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
}
@luislobo14rap
Copy link
Author

luislobo14rap commented Dec 23, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment