nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
111 lines (110 loc) • 3.29 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.$BaseConverter = void 0;
const constants_1 = require("./constants");
class $BaseConverter {
value;
unit;
constructor(value, unit) {
this.value = Number(value);
this.unit = unit ?? '';
}
$withPluralUnit(value, unit) {
const abs = Math.abs(value ?? this.value);
const u = unit ?? this.unit;
if (!u)
return String(abs);
let pluralized;
if (abs === 1) {
pluralized = u;
}
else if (constants_1.IRREGULAR_PLURALS?.[u]) {
pluralized = constants_1.IRREGULAR_PLURALS[u];
}
else if (constants_1.INVARIANT_UNITS.has(u)) {
pluralized = u;
}
else if (u.endsWith('foot')) {
pluralized = u.replace(/foot$/, 'feet');
}
else if (u.endsWith('inch')) {
pluralized = u.replace(/inch$/, 'inches');
}
else {
pluralized = constants_1.Y_TO_IES.has(u) ? u.replace(/y$/, 'ies') : `${u}s`;
}
return `${abs} ${pluralized}`;
}
$round(value, decimals = 2) {
const factor = 10 ** decimals;
return Math.round(value * factor) / factor;
}
$formatTo(value, target, shortLabels, options) {
const { style = 'plural', decimals = 2 } = options ?? {};
const rounded = this.$round(value, decimals);
switch (style) {
case 'compact':
return `${rounded}${shortLabels[target]}`;
case 'scientific':
return `${value.toExponential(decimals)} ${target}`;
default:
return this.$withPluralUnit(rounded, target);
}
}
valueOf() {
return this.value;
}
getValue() {
return this.value;
}
getUnit() {
return this.unit || 'unknown';
}
toString() {
return this.$withPluralUnit();
}
toObject() {
return { value: this.value, unit: this.unit || 'unknown' };
}
toJSON() {
return JSON.stringify(this.toObject());
}
abs() {
return new this.constructor(Math.abs(this.value), this.unit);
}
add(n) {
return new this.constructor(this.value + Number(n), this.unit);
}
subtract(n) {
return new this.constructor(this.value - Number(n), this.unit);
}
multiply(n) {
return new this.constructor(this.value * Number(n), this.unit);
}
divide(n) {
return new this.constructor(this.value / Number(n), this.unit);
}
round(decimals = 0) {
const rounded = this.$round(this.value, decimals);
return new this.constructor(rounded, this.unit);
}
gt(n) {
return this.value > Number(n);
}
lt(n) {
return this.value < Number(n);
}
eq(n) {
return this.value === Number(n);
}
format(decimals = 2) {
return this.$withPluralUnit(this.$round(this.value, decimals));
}
supportedUnits(category) {
if (category && category in constants_1.UNITS) {
return [...constants_1.UNITS[category]];
}
return Object.values(constants_1.UNITS).flat();
}
}
exports.$BaseConverter = $BaseConverter;