CodingNic

Operators & the Calculation Engine

Store the Selected Operation

Operators & the Calculation Engine 20 min read

Store the Selected Operation

Task

Create a method that stores the current number and selected operator when an operation button is pressed.

Open

Open:

js/calculator.js

Add chooseOperation() inside the Calculator class.

Add the method

javascript
chooseOperation(operation) {
  if (this.state.current === '' || this.state.current === null) {
    return;
  }

  if (this.state.previous !== null && this.state.operation) {
    this.equals();
  }

  this.state.previous = this.state.current;
  this.state.operation = operation;
  this.state.waitingForOperand = true;
  this.state.justCalculated = false;
}

The previous value records the first operand. The operation value records what should happen when the second operand arrives.

Test

Run:

javascript
calculator.clear();
calculator.inputDigit('8');
calculator.chooseOperation('+');
calculator.state;

Confirm that:

  • previous is "8"
  • operation is "+"
  • waitingForOperand is true

Checkpoint

The calculator now remembers the first operand and the operation selected by the user.