CodingNic

Operators & the Calculation Engine

Implement the Equals Operation

Operators & the Calculation Engine 30 min read

Implement the Equals Operation

Task

Use the stored state and calculation engine to implement =.

Open

Open:

js/calculator.js

Add equals() to the Calculator class.

Add the method

javascript
equals() {
  const { previous, current, operation } = this.state;

  if (previous === null || operation === null) {
    return Number(current);
  }

  try {
    const result = this.perform(previous, current, operation);

    this.state.current = String(result);
    this.state.lastExpression = `${previous} ${operation} ${current}`;
    this.state.previous = null;
    this.state.operation = null;
    this.state.waitingForOperand = true;
    this.state.justCalculated = true;

    return result;
  } catch (error) {
    this.state.current = 'Error';
    this.state.previous = null;
    this.state.operation = null;
    this.state.waitingForOperand = true;
    this.state.justCalculated = true;

    throw error;
  }
}

The method coordinates the workflow but delegates arithmetic to perform().

Connect the operator and equals buttons

In js/ui.js, extend the existing button handler:

javascript
if (action === 'operation') {
  calculator.chooseOperation(button.dataset.value);
}

if (action === 'equals') {
  try {
    calculator.equals();
  } catch (error) {
    console.error(error);
  }
}

updateDisplay();

Use the action names already present in your starter markup if they differ.

Test

In the browser:

  1. Click 8.
  2. Click +.
  3. Click 4.
  4. Click =.
  5. Confirm the display shows 12.

Then test:

  • 9 × 6 = → 54
  • 20 − 7 = → 13
  • 20 ÷ 5 = → 4

Also test division by zero and confirm the application does not silently produce an incorrect result.

Checkpoint

The calculator can now perform its four basic arithmetic operations from the browser interface.