JS Calculator Story #13

I’m still unable to figure out how to pass this user story #13 for this project.

My code meets the criteria of the user story itself which is:

User Story #13: If 2 or more operators are entered consecutively, the operation performed should be the last operator entered (excluding the negative (-) sign). For example, if 5 + * 7 = is entered, the result should be 35 (i.e. 5 * 7); if 5 * - 5 = is entered, the result should be -25 (i.e. 5 x (-5)).

However, there is a test case within the actual test scripts that I cannot figure out:

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

The sequence “5 * - + 5” = should produce an output of “10” : expected ‘-25’ to equal ‘10’

My handleEquals method uses JavaScripts eval() function, which interprets 5 * - + 5 as 5 * (-5) instead of 5 + 5, ignoring the first two operators. How can I go about the ignoring all but the last operator when there are consecutive operators?

My CodePen for this is:

Ive also used eval… one way to do it is:
Slice from after the first char of the string to the last(not including)
Inside your handleEquals, you will need two cases, one for which the length of said slice is greater than 2 and its last char is not the ‘-’ and check every char in your slice is an operand, in such a case just take the first character of your original input and the last two characters (because that is what the test wants you to do anyways…)

here is some solution ive forked yours:

but advise you to think about it first before you look… you will still have to solve case 14 afterwards though.

1 Like

Thank you for your help, I’ve managed to find a simpler approach IMO since posting the question. I ran a match() with a Regex pattern which returns a filtered string without the consecutive characters, ignoring the subtract character if it is last, which is then passed to eval().

var filtered = this.state.input.match(/(\*|\+|\/|-)?(\.|\-)?\d+/g).join('');
var sum = eval(filtered);
3 Likes

Hi, I have user story #14 left to pass for the JS Calculator which is:

User Story #14: Pressing an operator immediately following = should start a new calculation that operates on the result of the previous evaluation.

I thought it would be as simple as updating the state in my handleEquals() method to change the input to the result once I pressed the equals button but this doesn’t seem to be working and the test seems to be giving me a script error. I suspect it may be something to do with the way React updates state asynchronously. Please can you help solve this task. TIA.

console.log(typeof this.state.input, '=type of input')

Fix this and your calculator will work.
Ask me if something is not clear.