From 805f316310b40fbe94e3719cf2334f412517595b Mon Sep 17 00:00:00 2001 From: Timon Ringwald Date: Fri, 9 Sep 2022 01:20:36 +0200 Subject: [PATCH] evaluate math expressions --- evaluator.js | 1 + main.js | 22 +++++++++++++++++++--- templates/menu-item.html | 2 +- 3 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 evaluator.js diff --git a/evaluator.js b/evaluator.js new file mode 100644 index 0000000..8ab2a31 --- /dev/null +++ b/evaluator.js @@ -0,0 +1 @@ +onmessage = e => postMessage(eval(`parseInt(Math.round(${e.data}))`)); \ No newline at end of file diff --git a/main.js b/main.js index 45e0845..50b3b3d 100644 --- a/main.js +++ b/main.js @@ -113,18 +113,33 @@ async function addMenuItem(food) { }); const updateKcalAmount = () => { - if (!/[0-9]+/.test(itemAmount.value)) { - console.log("no match"); + if (!/^[0-9]+$/.test(itemAmount.value)) { return; } + const amount = parseInt(itemAmount.value); kcalAmount.textContent = parseInt(Math.round(food.kcal / 100 * amount)); 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.addEventListener("input", updateKcalAmount); + itemAmount.addEventListener("change", evaluateKcalAmount); updateKcalAmount(); foodMenu.appendChild(node); @@ -132,6 +147,7 @@ async function addMenuItem(food) { } function updateSummary() { + console.log("asd"); let sum = 0; for (let menuItem of foodMenu.querySelectorAll(".menu-item")) { diff --git a/templates/menu-item.html b/templates/menu-item.html index d2ea993..c977010 100644 --- a/templates/menu-item.html +++ b/templates/menu-item.html @@ -7,7 +7,7 @@