Hey guys so I took someone’s advice and basically refactored my calculator, with the objective of trying to keep it as simple and lightweight as possible. I created a calculator that passed all the tests with the exception of Test #15, aka the one dealing with negative numbers. So I created some code to deal with that, and now if I do the tests individually, it works. Eg, 3 + 5 * 6 - 2 / 4 equals 32.5, 2/7 equals 0.28…, and I can make numbers into negative numbers. I originally thought to do some kind of regex and only format it right before it calculates, but I felt that would be too difficult and complex for me. I wouldn’t even know where to begin honestly. So I came up with a solution where I have a variable that checks if something is a negative number.
Here’s the code.
let negativeNumCheck = /.*[\+\/\*\-]$/.test(input)
console.log(negativeNumCheck)
if(isNegativeNumber && inputtedOperator != "="){
inputtedOperator = ")" + inputtedOperator
isNegativeNumber = false
}else if(isNegativeNumber && inputtedOperator == "="){
setInput(prevVal => prevVal + ')')
setActivateCalculate(true)
}
if (inputtedOperator != "=" && inputtedOperator != "-"){
setInput(prevVal => prevVal + inputtedOperator)
}else if(negativeNumCheck && inputtedOperator == "-"){
setInput(prevVal => prevVal + "(" + inputtedOperator)
isNegativeNumber = true
}else if(negativeNumCheck == false && inputtedOperator == "-"){
setInput(prevVal => prevVal + inputtedOperator)
}else if(inputtedOperator === "=" && activateCalculate == false){
setActivateCalculate(true)
}
tl;dr, it checks if the last operator entered at that moment was an operator. if so, and if the current operator pressed is a minus sign, then put a parentheses with a minus sign. the user then can enter how many numbers he wants. if he presses an operator again, then add the closing sign before entering whatever operator he pressed. now negative numbers can be successfully calculated.
everything was working up until the negative number solution. then I added logic to fix that. if there’s something I’m missing or overlooking please let me know. and if I have to completely rewrite my calculating solution then please give me some tips?? thx so much for taking the time to read this.
Here’s my codepen