JavaScript Calculator - Tests not passing

My calculator seems working but doesn’t pass calculation tests.
Can someone please help me?
This is my Codepen link - https://codepen.io/mmmc-chrono/pen/XWYdgPv;

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0

Challenge: Front End Development Libraries Projects - Build a JavaScript Calculator

Link to the challenge:

I just fixed it but it is still not passing.

I noticed a bug with your = when you press it repeatedly.

Example: 6x3 = 18 then press = a few more times and it all goes squiffy when you then enter another operator.

Essentially you rerun your functions every time the = is clicked. You may need to add a logical safeguard to this.

FWIW, this was a tricky project for me to complete. I took an entirely different approach, using React and states to manage building of maths expressions and to safeguard against erroneous button presses, but my code was verbose and probably not especially elegant!

I changed line 149 from

$(“#display”).append(" = ").append(<br/><p>${total}</p>);

to

$(“#display”).text(total);

and passed all tests even before fixing bug that you said. It literally took me three days to figure that out. :joy:
BTW, thanks both of you for pointing out my mistakes and helping me.

1 Like

Hello @igorgetmeabrain , you can implement this pattern using:

  • Vanilla JavaScript
  • A finite state machine
  • A statecharts
  • The state design pattern
  • useReduce (React js)
  • There are a lot of libraries that you can use (Xstate, redux, etc).

The basic idea is that the app has a state, and can only transition to the next state if the “correct button is pressed” (event). So, we have a current state, an event and the next state (plus a function to move from one state to another):

const states =  {
      // RED is a state  
     'RED': {
         // tick is an event (button press)
        'tick': 'GREEN' // GREEN is the next state
      }, 
     'YELLOW': {
        'tick': 'RED'
      }, 
     'GREEN': {
        'tick': 'YELLLOW'
      }, 
   } 

// We pass the current state and an event: we get the next state  
const transition = (state, event) => states[state][event];

console.log(transition('RED','tick'));    // GREEN 
console.log(transition('YELLOW','tick')); // RED
console.log(transition('GREEN','tick'));  // YELLOW

// If the event (button press) is incorrect we get undefinded 
console.log(transition('RED','asdf')); // undefined 

The above code is only an example, there are better ways to implement this idea. I had more examples in my Portfolio

Cheers and happy coding :).

Notes:

1 Like

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