nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
48 lines (47 loc) • 1.34 kB
JavaScript
import { $BaseConverter } from './base.js';
import { UNITS } from './constants.js';
export class $Temperature extends $BaseConverter {
constructor(value, unit) {
super(value, unit);
}
static #toCelsius(value, from) {
switch (from) {
case 'fahrenheit':
return (value - 32) * (5 / 9);
case 'kelvin':
return value - 273.15;
default:
return value;
}
}
static #fromCelsius(value, to) {
switch (to) {
case 'fahrenheit':
return value * (9 / 5) + 32;
case 'kelvin':
return value + 273.15;
default:
return value;
}
}
to(target) {
const celsiusValue = $Temperature.#toCelsius(this.value, this.unit);
return $Temperature.#fromCelsius(celsiusValue, target);
}
toAll() {
const result = {};
for (const unit of UNITS.temp) {
result[unit] = this.to(unit);
}
return result;
}
formatTo(target, options) {
const value = this.to(target);
const shortLabels = {
celsius: '°C',
fahrenheit: '°F',
kelvin: 'K',
};
return this.$formatTo(value, target, shortLabels, options);
}
}