Please help me pass test 13 in the javascript calculator

I am using the mathjs library to handle my calculations. Please point towards how i could get started on solving test case 13

Here is a link to my code: https://codesandbox.io/s/calculator-hrk8d?file=/src/App.js

Hey Andrew,

great work so far!

  • Do you understand why the test fails?
  • What do you think is the cause of the wrong result?

Hey, sorry for the late reply.

Thank you :slight_smile:

The test fails because the library I am trying to use carries out the calculations in a different way than the test requires.

The wrong result is caused by the way the library is handles calculations i think

So if you input 5*-2,
MathJS thinks that you forgot to add brackets: 5 * (-2),
but the User Story wants you to only use the last operator: 5 - 2.

So what do you think is a good idea to handle this?

if i found a way to “tell” MathJs to ignore all other operators and evaluate only the last one

Yes, sounds good! Let us know if you can find one!

Another approach would be cleaning the input before you send it to MathJS.

closest i came to was this but it didnt offer a solution to my current problem

How would I go about cleaning the input?? :sweat_smile:

First I would try to find some examples, e.g.

5 + 2 => what should the program send to MathJS?
5 +- 2 => what should the program send to MathJS?
5 +* 2 => what should the program send to MathJS?
5 *- 2 => what should the program send to MathJS?

And then try to find a pattern behind it.

1 Like

Hey
I tried this


I’m still getting an error but i feel i’m somewhat closer to the solution. Could you please help me think through this some more?

Great work so far!

How about testing if there are more than one operator and if this is the case, only using the last one?

please give me a single example of how i would do that

I would first try to use a regex that checks if there are two of +-*/ consecutively.
If yes, then only use the last one of them.

would this /[-+*]{2,}/ work?
in this case i’m eliminating everything except the division operator

I think you’re almost there!

How about searching for every combination of at least 2 operations and replacing them?

  • +- => replace it with -
  • +* => replace it with *
  • *- => replace it with -

You could use the replace method with your regex and a custom replacer function:

It’s not that easy but I think you are able to solve it!

1 Like