From 01e4ae68b3c05727ee3ae9abe832ebfb159a2a97 Mon Sep 17 00:00:00 2001 From: irwanphan Date: Sat, 24 Oct 2020 17:29:26 +0700 Subject: [PATCH] check if the new one and the last one are operators, if they are, then remove last one --- script.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/script.js b/script.js index 4a47262..a4c58af 100644 --- a/script.js +++ b/script.js @@ -30,7 +30,21 @@ const displayHandler = () => { }; const appendText = (character) => { - operationString.innerHTML += character + checkRemoveOperator(operationString, character); + operationString.innerHTML += character; +} + +function checkRemoveOperator(str, newChar) { + let operators = ["-", "+", "/", "*"]; + let isOperator = false; //check is the last one is an operator + let isAnotherOperator = false; //check if the new one is an operator + for (const operator of operators){ + if(str.innerHTML.slice(-1) == operator) isOperator = true; + } + for (const operator of operators){ + if(newChar == operator) isAnotherOperator = true; + } + if (isOperator && isAnotherOperator) removeLastChar(); //if the new one and the last one are operators, remove last one } const removeLastChar = () => {