-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemperature.js
More file actions
39 lines (34 loc) · 1.66 KB
/
Copy pathtemperature.js
File metadata and controls
39 lines (34 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
export const scales = {
C: { label: 'Celsius (°C)', toK: value => value + 273.15, fromK: kelvin => kelvin - 273.15, symbol: '°C' },
F: { label: 'Fahrenheit (°F)', toK: value => (value + 459.67) * 5 / 9, fromK: kelvin => kelvin * 9 / 5 - 459.67, symbol: '°F' },
K: { label: 'Kelvin (K)', toK: value => value, fromK: kelvin => kelvin, symbol: 'K' },
R: { label: 'Rankine (°R)', toK: value => value * 5 / 9, fromK: kelvin => kelvin * 9 / 5, symbol: '°R' }
};
export function convertTemperature(value, from, to) {
if (!Number.isFinite(value)) throw new TypeError('value must be finite');
if (!scales[from] || !scales[to]) throw new RangeError('unknown temperature scale');
return scales[to].fromK(scales[from].toK(value));
}
if (typeof document !== 'undefined') {
const value = document.querySelector('#value');
const from = document.querySelector('#from');
const to = document.querySelector('#to');
const result = document.querySelector('#result');
for (const [key, scale] of Object.entries(scales)) {
from.add(new Option(scale.label, key));
to.add(new Option(scale.label, key));
}
from.value = 'C';
to.value = 'F';
function render() {
const numericValue = Number(value.value);
if (!Number.isFinite(numericValue)) {
result.textContent = 'Enter a numeric value';
return;
}
const converted = convertTemperature(numericValue, from.value, to.value);
result.textContent = `${numericValue} ${scales[from.value].symbol} = ${converted.toLocaleString(undefined, { maximumFractionDigits: 10 })} ${scales[to.value].symbol}`;
}
for (const element of [value, from, to]) element.addEventListener('input', render);
render();
}