Need some help on #13 of Building a Javascript Calc w/ React

I try not to do this, but I need some help. Attempted to finish the project quickly, but ended up coding myself into a corner.

Here’s the code: Hello code

I’ve finished the majority of the project and fulfill all but one error, " 13. If 2 or more operators are entered consecutively, the operation performed should be the last operator entered (excluding the negative (-) sign."

In particular, “The sequence “5 * - + 5” = should produce an output of “10” : expected ‘-25’ to equal ‘10’”. My code allows for the input, but does not perform the logic correctly as it doesn’t handle the operations (5*-+5 => 5*-5 => -25).

The workaround I do have, which parses the string and clears every operation beside the final one, breaks further logic. I also attempt to count the number of entered operations in a row, but this variable (operationCount) doesn’t function properly with my logic.

I’ve also attempted to parse the entire display value as array, which I’ll do again if suggested. Just seemed like more refactoring than necessary.

The problem is in my switch function, handleOp (=). I didn’t separate the numerical values either, which furthers the problem. I’m going to try from scratch again, but I figured since I was so close I should toss it up to the community before another go. Thank you!

@cbonilladev Everything pass for me!

I guess you have fixed it.

Yes, and I wanted to share my workaround.

I became stuck because I was trying to parse my answer in the “=” case (there’s only one switch operator) with only one operator. So, I wanted to press the equal sign to then clear the display of all but one operator.

That would then break expressions with multiple operators (3+5+2 => 3+52), so I tried splitting the string and parsing it as an array. Still didn’t work.

So I changed my focus to another event listener, the operator buttons. I was already counting the number of operators submitted in a row, so I just cleared the end of the string using a Regex command whenever too many operators were entered in a row.

Given I already had another similar function that lopped off the beginning 0 of the display string, I repurposed it that so 6+*-3 (2 operators in a row) would render 6±3.

That’s cool! I had used regex to check for multiple operators on pressing ‘=’.

But I can see a bug here - when you press ‘-’ and then either ‘*’ or ‘/’, it gets stuck.
e.g: ‘6 - * 7’ or ‘9 - / 3’

Could be because you aren’t incrementing the operation count when ‘-’ is pressed.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.