nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions and classes for everyday development needs.
365 lines (364 loc) • 10.8 kB
JavaScript
import { PREFIX_MULTIPLIERS } from './constants.js';
/**
* @class Represents a measurable unit and supports conversions between various types of units.
*
* Includes static methods for:
* - Length: meters, feet, kilometers, miles
* - Mass: kilograms, pounds, grams, ounces
* - Temperature: Celsius, Fahrenheit, Kelvin
* - Volume: liters, gallons
* - Area: square meters, square feet
* - Speed: km/h, mph
* - Time: hours, minutes, seconds, days
* - Digital Storage: kilobytes, megabytes, gigabytes
* - Energy: joules, calories
* - Pressure: atm, pascals
* - Frequency: Hz, kHz
*/
export class Unit {
#value;
#unit;
/**
* * Creates an instance of the Unit class.
* @param value The numeric value to work with.
* @param unit The unit type of the value (e.g., 'kg', 'm', 'kb').
*/
constructor(value, unit) {
this.#value = value;
this.#unit = unit;
}
/**
* @instance Returns the original value with unit (if passed in the constructor).
* @returns A string in the format "value unit".
*/
toString() {
return `${this.#value} ${this.#unit ?? ''}`.trim();
}
/**
* @instance Converts using scientific prefixes (e.g., kB to MB, mg to g).
*
* @param fromPrefix The SI prefix of the source unit.
* @param toPrefix The SI prefix of the target unit.
* @returns The converted numeric value.
*/
convertByPrefix(fromPrefix, toPrefix) {
return Unit.convertByPrefix(this.#value, fromPrefix, toPrefix);
}
/**
* @instance Converts from prefixed unit string to another (e.g., kB to MB, mg to g).
*
* @param from Prefixed unit string (e.g., 'kB', 'mg').
* @param to Target prefixed unit string (e.g., 'MB', 'g').
* @returns The converted numeric value.
*/
convertFromTo(from, to) {
return Unit.convertFromTo(this.#value, from, to);
}
/**
* @instance Converts the value using a static method name from the `Unit` class.
*
* - **N.B.** *Provides IntelliSense and type safety for method selection.*
*
* @param methodName - A static `Unit` method that accepts a number and returns a number.
* @returns The converted numeric value.
*/
convert(methodName) {
const method = Unit[methodName];
if (typeof method !== 'function') {
throw new Error(`Method ${methodName} is not a valid method!`);
}
return method(this.#value);
}
// ! ----- Static Conversion Methods ----- ! //
/**
* @static Converts a value using scientific prefixes (e.g., kB to MB, mg to g).
*
* @param value The value to convert.
* @param fromPrefix The SI prefix of the source unit.
* @param toPrefix The SI prefix of the target unit.
* @returns The converted numeric value.
*/
static convertByPrefix(value, fromPrefix, toPrefix) {
const fromMultiplier = PREFIX_MULTIPLIERS[fromPrefix];
const toMultiplier = PREFIX_MULTIPLIERS[toPrefix];
return (value * fromMultiplier) / toMultiplier;
}
/**
* @static Converts from prefixed unit string to another (e.g., kB to MB, mg to g).
*
* @param value The numeric value.
* @param from Prefixed unit string (e.g., 'kB', 'mg').
* @param to Target prefixed unit string (e.g., 'MB', 'g').
* @returns The converted numeric value.
*/
static convertFromTo(value, from, to) {
const extractPrefix = (str) => {
const match = str.match(/^(da|[yzafpnμumcdhkMGTPEZY]?)(.+)$/);
if (!match)
throw new Error(`Invalid unit format: ${str}`);
return [match[1], match[2]];
};
const [fromPrefix, fromUnit] = extractPrefix(from);
const [toPrefix, toUnit] = extractPrefix(to);
if (fromUnit !== toUnit) {
throw new Error(`Mismatched units: ${fromUnit} vs ${toUnit}`);
}
return Unit.convertByPrefix(value, fromPrefix, toPrefix);
}
/** Converts meters to feet. */
static metersToFeet(m) {
return m * 3.28084;
}
/** Converts feet to meters. */
static feetToMeters(ft) {
return ft / 3.28084;
}
/** Converts kilometers to miles. */
static kmToMiles(km) {
return km * 0.621371;
}
/** Converts miles to kilometers. */
static milesToKm(mi) {
return mi / 0.621371;
}
/** Converts kilograms to pounds. */
static kgToLbs(kg) {
return kg * 2.20462;
}
/** Converts pounds to kilograms. */
static lbsToKg(lbs) {
return lbs / 2.20462;
}
/** Converts grams to ounces. */
static gramsToOunces(g) {
return g * 0.035274;
}
/** Converts ounces to grams. */
static ouncesToGrams(oz) {
return oz / 0.035274;
}
/** Converts Celsius to Fahrenheit. */
static celsiusToFahrenheit(c) {
return (c * 9) / 5 + 32;
}
/** Converts Fahrenheit to Celsius. */
static fahrenheitToCelsius(f) {
return ((f - 32) * 5) / 9;
}
/** Converts Celsius to Kelvin. */
static celsiusToKelvin(c) {
return c + 273.15;
}
/** Converts Kelvin to Celsius. */
static kelvinToCelsius(k) {
return k - 273.15;
}
/** Converts Fahrenheit to Kelvin. */
static fahrenheitToKelvin(f) {
return ((f - 32) * 5) / 9 + 273.15;
}
/** Converts Kelvin to Fahrenheit. */
static kelvinToFahrenheit(k) {
return ((k - 273.15) * 9) / 5 + 32;
}
/** Converts milliliters to liters. */
static mlToLiters(ml) {
return ml / 1000;
}
/** Converts liters to milliliters. */
static litersToMl(l) {
return l * 1000;
}
/** Converts gallons to milliliters. */
static gallonsToMl(gal) {
return gal * 3785.41;
}
/** Converts milliliters to gallons. */
static mlToGallons(ml) {
return ml / 3785.41;
}
/** Converts liters to gallons. */
static litersToGallons(l) {
return l * 0.264172;
}
/** Converts gallons to liters. */
static gallonsToLiters(gal) {
return gal / 0.264172;
}
/** Converts square meters to square feet. */
static sqmToSqft(sqm) {
return sqm * 10.7639;
}
/** Converts square feet to square meters. */
static sqftToSqm(sqft) {
return sqft / 10.7639;
}
/** Converts kilometers per hour to miles per hour. */
static kmphToMph(kmph) {
return kmph * 0.621371;
}
/** Converts miles per hour to kilometers per hour. */
static mphToKmph(mph) {
return mph / 0.621371;
}
/** Converts minutes to hours. */
static minutesToHours(min) {
return min / 60;
}
/** Converts seconds to minutes. */
static secondsToMinutes(sec) {
return sec / 60;
}
/** Converts hours to days. */
static hoursToDays(hr) {
return hr / 24;
}
/** Converts hours to minutes. */
static hoursToMinutes(h) {
return h * 60;
}
/** Converts minutes to seconds. */
static minutesToSeconds(m) {
return m * 60;
}
/** Converts days to hours. */
static daysToHours(d) {
return d * 24;
}
/** Converts megabytes to gigabytes. */
static mbToGb(mb) {
return mb / 1024;
}
/** Converts gigabytes to megabytes. */
static gbToMb(gb) {
return gb * 1024;
}
/** Converts kilobytes to megabytes. */
static kbToMb(kb) {
return kb / 1024;
}
/** Converts kilobytes to gigabytes. */
static kbToGb(kb) {
return kb / (1024 * 1024);
}
/** Converts gigabytes to kilobytes. */
static gbToKb(gb) {
return gb * 1024 * 1024;
}
/** Converts bytes to kilobytes. */
static bytesToKb(bytes) {
return bytes / 1024;
}
/** Converts kilobytes to bytes. */
static kbToBytes(kb) {
return kb * 1024;
}
/** Converts megabytes to kilobytes. */
static mbToKb(mb) {
return mb * 1024;
}
/** Converts gigabytes to terabytes. */
static gbToTb(gb) {
return gb / 1024;
}
/** Converts terabytes to gigabytes. */
static tbToGb(tb) {
return tb * 1024;
}
/** Converts joules to calories. */
static joulesToCalories(j) {
return j * 0.239006;
}
/** Converts calories to joules. */
static caloriesToJoules(cal) {
return cal / 0.239006;
}
/** Converts calories to kilojoules. */
static caloriesToKJoules(cal) {
return cal / 0.239006 / 1000;
}
/** Converts kilojoules to calories. */
static kJoulesToCalories(kj) {
return kj * 1000 * 0.239006;
}
/** Converts atmospheres to pascals. */
static atmToPascal(atm) {
return atm * 101325;
}
/** Converts pascals to atmospheres. */
static pascalToAtm(pa) {
return pa / 101325;
}
/** Converts bar to pascals. */
static barToPascal(bar) {
return bar * 100000;
}
/** Converts pascals to bar. */
static pascalToBar(pa) {
return pa / 100000;
}
/** Converts hertz to kilohertz. */
static hzToKHz(hz) {
return hz / 1000;
}
/** Converts kilohertz to hertz. */
static kHzToHz(khz) {
return khz * 1000;
}
/** Converts hertz to megahertz. */
static hzToMHz(hz) {
return hz / 1_000_000;
}
/** Converts megahertz to hertz. */
static mHzToHz(mhz) {
return mhz * 1_000_000;
}
/** Converts kilohertz to megahertz. */
static kHzToMHz(khz) {
return khz / 1000;
}
/** Converts megahertz to kilohertz. */
static mHzToKHz(mhz) {
return mhz * 1000;
}
/** Converts centimeters to meters. */
static cmToMeters(cm) {
return cm / 100;
}
/** Converts meters to centimeters. */
static metersToCm(m) {
return m * 100;
}
/** Converts millimeters to meters. */
static mmToMeters(mm) {
return mm / 1000;
}
/** Converts meters to millimeters. */
static metersToMm(m) {
return m * 1000;
}
/** Converts square kilometers to square meters. */
static sqkmToSqm(sqkm) {
return sqkm * 1_000_000;
}
/** Converts square meters to square kilometers. */
static sqmToSqkm(sqm) {
return sqm / 1_000_000;
}
/** Converts square feet to square inches. */
static sqftToSqin(sqft) {
return sqft * 144;
}
/** Converts square inches to square feet. */
static sqinToSqft(sqin) {
return sqin / 144;
}
/** Converts watts to kilowatts. */
static wattsToKw(w) {
return w / 1000;
}
/** Converts kilowatts to watts. */
static kwToWatts(kw) {
return kw * 1000;
}
}