evaluate math expressions

This commit is contained in:
Timon Ringwald 2022-09-09 01:20:36 +02:00
parent c333285116
commit 805f316310
3 changed files with 21 additions and 4 deletions

1
evaluator.js Normal file
View File

@ -0,0 +1 @@
onmessage = e => postMessage(eval(`parseInt(Math.round(${e.data}))`));

22
main.js
View File

@ -113,18 +113,33 @@ async function addMenuItem(food) {
}); });
const updateKcalAmount = () => { const updateKcalAmount = () => {
if (!/[0-9]+/.test(itemAmount.value)) { if (!/^[0-9]+$/.test(itemAmount.value)) {
console.log("no match");
return; return;
} }
const amount = parseInt(itemAmount.value); const amount = parseInt(itemAmount.value);
kcalAmount.textContent = parseInt(Math.round(food.kcal / 100 * amount)); kcalAmount.textContent = parseInt(Math.round(food.kcal / 100 * amount));
updateSummary(); updateSummary();
};
const evaluateKcalAmount = () => {
if (/^[0-9]+$/.test(itemAmount.value)) {
return;
}
const evaluator = new Worker("evaluator.js");
evaluator.postMessage(itemAmount.value);
evaluator.onmessage = e => {
const amount = Math.max(parseInt(e.data), 0);
itemAmount.value = amount;
kcalAmount.textContent = parseInt(Math.round(food.kcal / 100 * amount));
updateSummary();
};
} }
console.log(food.avg_amount);
itemAmount.value = food.avg_amount ?? 100; itemAmount.value = food.avg_amount ?? 100;
itemAmount.addEventListener("input", updateKcalAmount); itemAmount.addEventListener("input", updateKcalAmount);
itemAmount.addEventListener("change", evaluateKcalAmount);
updateKcalAmount(); updateKcalAmount();
foodMenu.appendChild(node); foodMenu.appendChild(node);
@ -132,6 +147,7 @@ async function addMenuItem(food) {
} }
function updateSummary() { function updateSummary() {
console.log("asd");
let sum = 0; let sum = 0;
for (let menuItem of foodMenu.querySelectorAll(".menu-item")) { for (let menuItem of foodMenu.querySelectorAll(".menu-item")) {

View File

@ -7,7 +7,7 @@
<div class="menu-item-amount-container"> <div class="menu-item-amount-container">
<span class="menu-item-kcal-for-amount"></span> <span class="menu-item-kcal-for-amount"></span>
<span class="menu-item-kcal-unit">kcal</span>/<input class="menu-item-amount" type="number" pattern="[0-9]+"><span class="menu-item-unit"></span> <span class="menu-item-kcal-unit">kcal</span>/<input class="menu-item-amount" type="text" pattern="[0-9]+"><span class="menu-item-unit"></span>
</div> </div>
<span class="menu-item-info-container"> <span class="menu-item-info-container">