monorepo/kifu/kifu-pwa/converter.js

51 lines
1.5 KiB
JavaScript

import init, { coreapp_new, coreapp_dispatch } from "./kifu_wasm.js";
const inputField = document.getElementById('input-temp');
const fromUnitField = document.getElementById('input-unit');
const toUnitField = document.getElementById('output-unit');
const outputField = document.getElementById('output-temp');
const form = document.getElementById('converter');
function convertTemp(value, fromUnit, toUnit) {
if (fromUnit === 'c') {
if (toUnit === 'f') {
return value * 9 / 5 + 32;
} else if (toUnit === 'k') {
return value + 273.15;
}
return value
}
if (fromUnit === 'f') {
if (toUnit === 'c') {
return (value - 32) * 5 / 9;
} else if (toUnit === 'k') {
return (value + 459.67) * 5 / 9;
}
return value;
}
if (fromUnit === 'k') {
if (toUnit === 'c') {
return value - 273.15;
} else if (toUnit === 'f') {
return value * 9 / 5 - 459.67;
}
return value;
}
throw new Error('Invalid unit');
}
form.addEventListener('input', () => {
const inputTemp = parseFloat(inputField.value);
const fromUnit = fromUnitField.value;
const toUnit = toUnitField.value;
const outputTemp = convertTemp(inputTemp, fromUnit, toUnit);
outputField.value = (Math.round(outputTemp * 100) / 100) + ' ' + toUnit.toUpperCase();
});
init().then(async () => {
let app = coreapp_new();
await coreapp_dispatch(app);
console.log("kifu_wasm successfully initted");
});