@techmely/utils
Version:
Collection of helpful JavaScript / TypeScript utils
63 lines (59 loc) • 2.04 kB
JavaScript
/*!
* @techmely/utils
* Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com>
* MIT Licensed
*/
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/bytes.ts
var bytes_exports = {};
__export(bytes_exports, {
formatBytes: () => formatBytes,
formatDecimals: () => formatDecimals
});
module.exports = __toCommonJS(bytes_exports);
var formatBytes = (bytes, options) => {
const sizes = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const { numberOfDecimals = 0 } = options ?? {};
if (!bytes || bytes <= 0) {
return "0 bytes";
}
if (bytes === 1) {
return "1 byte";
}
const base = 1e3;
const exponent = Math.trunc(Math.log(bytes) / Math.log(base));
const rawValue = bytes / base ** exponent;
let [whole, partial = ""] = rawValue.toString().split(".");
if (numberOfDecimals > 0) {
const count = numberOfDecimals - partial.length;
if (count > 0) {
partial += "0".repeat(count);
}
whole += `.${partial.slice(0, numberOfDecimals)}`;
}
const abbreviationSuffix = sizes[exponent];
return `${whole} ${abbreviationSuffix}`;
};
var formatDecimals = (bytes = 0) => bytes >= 1e9 ? 2 : 0;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
formatBytes,
formatDecimals
});