From 588ff133040e6f197d6eb742232d320f2b8c6991 Mon Sep 17 00:00:00 2001 From: NetMan <13informatyka14@gmail.com> Date: Tue, 16 Jan 2024 20:22:42 +0100 Subject: [PATCH] JS: Clearing, displaying via new function, new key presses --- script.js | 64 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/script.js b/script.js index 6bc38d8..6854e08 100644 --- a/script.js +++ b/script.js @@ -48,7 +48,7 @@ function execute(operation) { } } -let operation = { +const operationInitial = { a: "0", operator: "", b: "", @@ -57,15 +57,36 @@ let operation = { outputOfEquasion: false, } +let operation = {}; +Object.assign(operation, operationInitial); + let readyForEquasion = ""; +function clearDisplay() { + signGui.textContent = ""; + valueGui.textContent = `0`; +} + +function clear() { + clearDisplay(); + Object.assign(operation, operationInitial); +} + +function populateDisplay(operation) { + signGui.textContent = `${operation.operator}`; + if (operation.addToA) { + valueGui.textContent = `${operation.a}`; + } else { + valueGui.textContent = `${operation.b}`; + } +} + function click(value) { if (!isNaN(+value)) { if (operation.outputOfEquasion) { operation.a = value; operation.outputOfEquasion = false; - signGui.textContent = ""; - valueGui.textContent = `${operation.a}`; + populateDisplay(operation); operation.addToA = true; } else { if (operation.addToA) { @@ -73,24 +94,24 @@ function click(value) { operation.a = ""; } operation.a += value; - valueGui.textContent = `${operation.a}`; + populateDisplay(operation); } else { if (operation.b == "0") { operation.b = ""; } operation.b += value; operation.readyForEquasion = true; - valueGui.textContent = `${operation.b}`; + populateDisplay(operation); } } } else if (value == "=") { execute(operation); - signGui.textContent = value; + populateDisplay(operation); } else { if (operation.operator == "") { operation.addToA = !operation.addToA; operation.operator = value; - signGui.textContent = value; + populateDisplay(operation); } if (operation.addToA) { operation.operator = value; @@ -165,5 +186,34 @@ function numbers(e) { let passLetter = e.key.toLowerCase(); if (!isNaN(+passLetter)) { click(passLetter); + } else if (passLetter == "escape") { + clear(); + } else if (passLetter == "backspace") { + if (!operation.outputOfEquasion) { + if (operation.addToA) { + operation.a = operation.a.substring(0, operation.a.length - 1); + if (operation.a.length < 1) { + operation.a = "0"; + } + } else { + operation.b = operation.b.substring(0, operation.b.length - 1); + if (operation.b.length < 1) { + operation.b = "0"; + } + } + populateDisplay(operation); + } else { + clear(); + } + } else if (passLetter == "+" + || passLetter == "-" + || passLetter == "*" + || passLetter == "/" + || passLetter == "=") { + click(passLetter); + } else if (passLetter == "enter") { + click("="); + } else { + console.log(passLetter); } } \ No newline at end of file