@draconides/format
Version:
Formatter function
53 lines (52 loc) • 2.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const unit_1 = require("@draconides/unit");
const getUnit = (conversion, style, format) => {
if (style === 'byte') {
if (format === 'full') {
return conversion === 'binary' ? unit_1.computing.SizeByteBinaryFull : unit_1.computing.SizeByteDecimalFull;
}
return conversion === 'binary' ? unit_1.computing.SizeByteBinaryMinimal : unit_1.computing.SizeByteDecimalMinimal;
}
if (format === 'full') {
return conversion === 'binary' ? unit_1.computing.SizeOctetBinaryFull : unit_1.computing.SizeOctetDecimalFull;
}
return conversion === 'binary' ? unit_1.computing.SizeOctetBinaryMinimal : unit_1.computing.SizeOctetDecimalMinimal;
};
/* eslint-disable tsdoc/syntax */
/* eslint-disable jsdoc/require-param */
/* eslint-disable jsdoc/check-param-names */
/**
* Format a byte value into a readable string
* @param bytes Byte to format
* @param options Option object
* @param options.decimals Number of decimals
* @param options.formatter Function to formate the number
* @param options.conversion Type of conversion
* @param options.style Type of the unit
* @param options.unitFormat Unit format
* @returns formated bytes
*/
const formatBytes = (bytes, options = {}) => {
const { decimals = 2, formatter = (value) => value.toString(), conversion = 'binary', style = 'byte', unitFormat = 'minimal', } = options;
// Get unit
const unit = getUnit(conversion, style, unitFormat);
// Return default
if (!bytes || bytes === 0) {
return `0 ${unit[0]}`;
}
// Get the weight of a kile
const kilo = conversion === 'binary' ? 1024 : 1000;
// Get the decimals
const numberOfDecimals = decimals < 0 ? 0 : decimals;
// Calculate the power index
let power = Math.floor(Math.log(bytes) / Math.log(kilo));
// Floor the power index
if (power > unit.length) {
power = unit.length;
}
// Calculate and formats the byte value
const value = parseFloat((bytes / Math.pow(kilo, power)).toFixed(numberOfDecimals));
return `${formatter(value)} ${unit[power]}`;
};
exports.default = formatBytes;