forked from svrjs/svrjs
Make sizify() function more concise and readable
This commit is contained in:
parent
0318047078
commit
64b4e056cb
1 changed files with 17 additions and 18 deletions
|
@ -1,26 +1,25 @@
|
||||||
function sizify(bytes, addI) {
|
function sizify(bytes, addI) {
|
||||||
if (bytes == 0) return "0";
|
if (bytes === 0) return "0";
|
||||||
if (bytes < 0) bytes = -bytes;
|
if (bytes < 0) bytes = -bytes;
|
||||||
|
|
||||||
const prefixes = ["", "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"];
|
const prefixes = ["", "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"];
|
||||||
let prefixIndex = Math.floor(
|
const prefixIndex = Math.min(
|
||||||
Math.log2 ? Math.log2(bytes) / 10 : Math.log(bytes) / (Math.log(2) * 10),
|
Math.floor(Math.log2(bytes) / 10),
|
||||||
|
prefixes.length - 1,
|
||||||
);
|
);
|
||||||
if (prefixIndex >= prefixes.length - 1) prefixIndex = prefixes.length - 1;
|
const prefixIndexTranslated = Math.pow(2, 10 * prefixIndex);
|
||||||
let prefixIndexTranslated = Math.pow(2, 10 * prefixIndex);
|
const decimalPoints = Math.max(
|
||||||
let decimalPoints =
|
2 - Math.floor(Math.log10(bytes / prefixIndexTranslated)),
|
||||||
2 -
|
0,
|
||||||
Math.floor(
|
);
|
||||||
Math.log10
|
|
||||||
? Math.log10(bytes / prefixIndexTranslated)
|
const size =
|
||||||
: Math.log(bytes / prefixIndexTranslated) / Math.log(10),
|
|
||||||
);
|
|
||||||
if (decimalPoints < 0) decimalPoints = 0;
|
|
||||||
return (
|
|
||||||
Math.ceil((bytes / prefixIndexTranslated) * Math.pow(10, decimalPoints)) /
|
Math.ceil((bytes / prefixIndexTranslated) * Math.pow(10, decimalPoints)) /
|
||||||
Math.pow(10, decimalPoints) +
|
Math.pow(10, decimalPoints);
|
||||||
prefixes[prefixIndex] +
|
const prefix = prefixes[prefixIndex];
|
||||||
(prefixIndex > 0 && addI ? "i" : "")
|
const suffix = prefixIndex > 0 && addI ? "i" : "";
|
||||||
);
|
|
||||||
|
return size + prefix + suffix;
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = sizify;
|
module.exports = sizify;
|
||||||
|
|
Reference in a new issue