ReactJS calculator help

Hello,

I followed a tutorial for the front end framework certification, and I got stuck at the calculator challenge, I did my own implementation then changed it to a tutorial I followed online, and the issue is that I cant pass test 13, I cant make the calculator replace both operators after I typed a “-” after any other signs. The test is 5 * - + 5 should equal 10. Can I get any advice on how can I make this implementation, the link to the pen is below.

Calculator pen -> https://codepen.io/tanasievlad246/pen/QWjKLOY?editors=0010

Hi, eval() built in function should evaluate it for you directly. Another way is using regular expressions.

eval() is not going to help with an expression like 5 * - + 5. And a regexp is only useful for scanning and tokenizing the expression, but not for evaluating anything.

The idea with the calculator challenge is to implement a state machine that emulates a real physical calculator. It’s not an easy challenge by any means. The curriculum has introduced the tools you’ll need, but the complexity is far beyond anything the challenges have asked you to implement. Be prepared for this one to take much more time than any of the other projects.

Hi @Vlad246, a couple of days ago I finished the calculator project (almost, I havent’t tested), is also a reactjs calculator[0], but I used a statechart library (xstate) and used (mostly) this diagram.

What I can see in your project you had used 3 explicit states:

  • currentNumber
  • operatorFlag
  • decimalFlag

And some implicit states like:

  • this.state.currentNumber !==“0”

So, an idea is add and explicit state for the “-” token and deal with it directly. The problem with this approach is that you probably will have to deal with the rest of your implicit states. That can be time consuming, but if you only want to pass the tests, I think is doable.

The option of use a reg exp, I think, that can be doable if you: decouple the input (button clicks) from what is displayed in the screen and also use (at least) 3 differents input ( operand , operator, operand) but at that point you’re basically defining a formal language/grammar by hand[1]

Cheers and happy coding :slight_smile:

note:

[0] https://github.com/diegoperezm/react-xstate-calc

[1] if you are interested in that you can try: jison

1 Like