I have been working on this calculator for two weeks now. Many blood sweat and tears were poured into this little thing. I chose a different solution than I think most people did. My calculator calculates each time the operator is pressed and displays the result each time, as opposed to using some sort of string manipulation that seems to be popular with most people. I don’t want to deal with regex or any kind of string manipulation (unless necessary) for this challenge. I know you’re not supposed to use global variables in react but I just wanted to get this done and I found that it does the job.
So I’m stuck on #14 (as well as another one but I’ll figure that one out later). I can get the result when I press the equals button. But if I press another operator after that, it kind of resets and doesn’t continue based on the sum of the previous calculation. Can anyone give me a hint on what to look out for? I know the culprit lies in my calculate function but I don’t understand why the sum is being zeroed out after I press an operator.
Here’s my if statement to check if it’s good to calculate or not
if(canCalculate){
calculate()
setPrevVal(sum)
setInput(sum)
// setOperator(null)
canCalculate = false;
isDecimalAllowed = true
}
function calculate(){
if(hitEqualsButton){
console.log("Hit equals is true.")
}
let op
if(prevOp == null || hitEqualsButton){
op = operator
hitEqualsButton = false
}else{
op = prevOp
}
console.log("Calculating using this operator...")
console.log(op)
let prevValHolder = Number(prevVal)
let inputHolder = Number(input)
switch(op){
case "add":
sum = prevValHolder + inputHolder
break;
case "subtract":
if(prevValHolder == 0){
sum = inputHolder - 0
}else{
sum = prevValHolder - inputHolder
}
break;
case "multiply":
if(prevValHolder == 0){
sum = inputHolder * 1
}else{
sum = prevValHolder * inputHolder
}
break;
case "divide":
if(prevValHolder == 0 && sum == 0){
sum = inputHolder / 1
}else{
sum = prevValHolder / inputHolder
}
break;
default:
sum = sum
break;
}
setPrevOp(operator)
console.log("Sum: ")
console.log(sum)
}
I really wanna get to the pomodoro clock…