format-byte-size
Version:
[DEPRECATED] A TypeScript library to format byte values into human-readable strings and parse them back.
112 lines (109 loc) • 2.45 kB
JavaScript
;
// src/constants.ts
var DECIMAL_UNITS = [
"B",
"KB",
"MB",
"GB",
"TB",
"PB",
"EB",
"ZB",
"YB"
];
var BINARY_UNITS = [
"B",
"KiB",
"MiB",
"GiB",
"TiB",
"PiB",
"EiB",
"ZiB",
"YiB"
];
var DECIMAL_BASE = 1e3;
var BINARY_BASE = 1024;
var UNIT_MAP = {
// Decimal units (base 1000)
b: 1,
byte: 1,
bytes: 1,
kb: 1e3,
mb: 1e3 ** 2,
gb: 1e3 ** 3,
tb: 1e3 ** 4,
pb: 1e3 ** 5,
eb: 1e3 ** 6,
zb: 1e3 ** 7,
yb: 1e3 ** 8,
// Binary units (base 1024)
kib: 1024,
mib: 1024 ** 2,
gib: 1024 ** 3,
tib: 1024 ** 4,
pib: 1024 ** 5,
eib: 1024 ** 6,
zib: 1024 ** 7,
yib: 1024 ** 8
};
// src/index.ts
function formatBytes(bytes, options) {
if (typeof bytes !== "number") {
throw new TypeError("Input bytes must be a number");
}
const {
decimalPlaces = 2,
useBinary = false,
fixedDecimals = false,
includeUnitSpace = true
} = options || {};
const units = useBinary ? BINARY_UNITS : DECIMAL_UNITS;
const base = useBinary ? BINARY_BASE : DECIMAL_BASE;
const space = includeUnitSpace ? " " : "";
if (bytes === 0) {
return `0${space}Bytes`;
}
const isNegative = bytes < 0;
const absoluteBytes = Math.abs(bytes);
const unitIndex = absoluteBytes < 1 ? 0 : Math.min(
Math.floor(Math.log(absoluteBytes) / Math.log(base)),
units.length - 1
);
const value = absoluteBytes / Math.pow(base, unitIndex);
const formattedValue = fixedDecimals ? value.toFixed(decimalPlaces) : parseFloat(value.toFixed(decimalPlaces)).toString();
const sign = isNegative ? "-" : "";
const unit = units[unitIndex];
return `${sign}${formattedValue}${space}${unit}`;
}
function parseBytes(sizeString) {
if (typeof sizeString !== "string") {
throw new TypeError("Input sizeString must be a string");
}
const trimmed = sizeString.trim();
if (!trimmed) {
return null;
}
const match = trimmed.match(/^(-?\d+(?:\.\d+)?)\s*([a-z]+)?$/i);
if (!match) {
return null;
}
const [, valueStr, unit] = match;
const value = parseFloat(valueStr);
if (isNaN(value)) {
return null;
}
if (!unit) {
return value;
}
const unitLower = unit.toLowerCase();
const multiplier = UNIT_MAP[unitLower];
if (multiplier === void 0) {
return null;
}
return value * multiplier;
}
exports.formatBytes = formatBytes;
exports.parseBytes = parseBytes;
//# sourceMappingURL=index.cjs.map
//# sourceMappingURL=index.cjs.map