# React calculator: failing consecutive operators

React calculator: failing consecutive operators
0

#1

I keep failing this test. Basically, if you input:

"The sequence "5 * - + 5" = should produce an output of "10" : expected '-25' to equal '10'"

the multiplication will always take precedence over any operator. It only involves multiplication, it works fine if it´s any other operator. Any idea on how to fix it?

#2

I think I understand what you’re missing. You aren’t supposed to process ALL the operator tokens, only the last one (so 5+5). Think of it as the user changing their mind mid-expression:
“5”: I want to take five, and…
“*”: Multiply it by…
“-”: No, I mean subtract by…
“+”: No, I mean add to…
5. (Calculator displays 10)

#3

Thanks for the reply. I just thought math.eval would do that for me. So I should basically add something to the equals action?

#4

That’s what I did, but if you want to use math.js, you could do that. The issue is the string you’re feeding to it. You need a way to ONLY add the last operator to state.value instead of this line:

this.setState(prevState => ({
value: `\${prevState.value}\${result}`.replace(/^0+\B/, "")
}));

#5

Thanks. Not sure I follow though.
When you say “That´s what I did”, do you mean adding some sort of checker to the equals?

#6

Sorry, I misunderstood what you said. I actually processed the input myself, assessing whether the calculator was getting fed a digit, operator, or an equals key. Depending on that, I had different handlers that responded appropriately (pseudocode spoiler below, but only if you abandon the math.js library. My suggestion to make sure the state.value string is the easiest way to get to where you want from where you are.

• digit:
• last input was a digit: modified state with the current number being input
• last input was an operator: executed the last operator pressed.
• operator:
• last input was a digit: finalized the number being input in this.state
• last input was an operator: replaced the “last input”
• equals:
• processed the growing expression depending on what the last input was.

#7

Thanks, I just don´t know how to apply this:
“My suggestion to make sure the state.value string is the easiest way to get to where you want from where you are”
I´m completely stuck, and I think I´m quitting.

#8

You have to develop frustration tolerance if you want to be a programmer. Don’t give up. You are very close to a solution.

Hint: ask yourself what the value of state.value is every time you update it.
Hint: You could have the callback you pass to this.setState also use a console.log to print out the new value, so you don’t have to guess what you are eventually passing to `math.eval.