Stuck on Calculator

Stuck on Calculator
0

Ok so it’s been a couple of days and many many tries to build a Calculator with React and Javascript.
I have erased everything and started from zero a couple of times, but I still can’t get my head around the problem. How should I be looking at this problem? I’ve tried strings, arrays, splice methods, push, pop, shift, unshift. The closest I’ve got was 13 test completed.

One of the test that failed was that the calculator had to only consider the last operator entered. I had forgotten about this test item and made my calculator would only accept one operator and delete the previous operator. So I had to go back and rewrite that part of the code.

I could really use some advice.

I think I might have coder’s block.

Posting a link to your repo/code would help identify the problem with your approach. There is no one “right decision” or “one and only correct way to do things”.

1 Like

@NickEU

Ok so I’m almost there. Passed 15 of 16 tests.

13. If 2 or more operators are entered consecutively, the operation performed should be the last operator entered (excluding the negative (-) sign

SyntaxError: invalid increment/decrement operand

Here is my codepen project: https://codepen.io/ezequiel_/pen/eYOJKaw

I brain is fried, it’s been almost a week that I’m working on this calculator.
Could really use some help.

Thanks!

You really should creates some variables instead of referencing things like arrayNumbers[i], arrayNumbers[i+1], arrayNumbers[i+2]. It would help you and others reviewing your code to know what you think you are comparing.

In the case of entering 5*-5=, the following if statement evaluates to true:

if(arrayNumbers[i+1]==="-"){

When 'i = 1`you then check:

if(operators.test(arrayNumbers[i+2])){ // checking operators.test(5)

this is going to evaluate to false and the following code will execute:

stringToEvaluate = stringToEvaluate + arrayNumbers[i] + arrayNumbers[i+1]

At this point in the code, stringToEvaluate is 5, arrayNumberst[i] is,arrayNumbers[i+1]is-, so you assignstringToEvaluatethe value5-`.

Then, when i = 2, you end up adding - to the end of stringToEvaluate, because the following if statement evaluates to false.

if(operators.test(arrayNumbers[i+1])){

Finally, when i = 3, you add 5 to the end of stringToEvaluate, because the same if statement above evaluates to false.

This means you are left with the string 5*--5 to evaluate, which is not possible and errors out.

Thanks for your insight @RandellDawson. I will look into this and get back to you.

I finally got all the tests to pass. :sweat_smile: @RandellDawson

https://codepen.io/ezequiel_/pen/zYOqBeo