CodingNic

Operators & the Calculation Engine

Build the Calculation Engine

Operators & the Calculation Engine 25 min read

Build the Calculation Engine

Task

Create one reusable function that performs the four basic arithmetic operations.

Open

Open:

js/calculator.js

Add perform() to the Calculator class.

Add the method

javascript
perform(left, right, operation) {
  const a = Number(left);
  const b = Number(right);

  switch (operation) {
    case '+':
      return a + b;

    case '-':
      return a - b;

    case '*':
      return a * b;

    case '/':
      if (b === 0) {
        throw new Error('Cannot divide by zero');
      }
      return a / b;

    default:
      return b;
  }
}

Keep this method focused. It should calculate a result; it should not update the DOM or create history entries.

Test

Try:

javascript
calculator.perform('10', '5', '+');
calculator.perform('10', '5', '-');
calculator.perform('10', '5', '*');
calculator.perform('10', '5', '/');

The results should be 15, 5, 50, and 2.

Also test:

javascript
calculator.perform('10', '0', '/');

It should throw the divide-by-zero error.

Checkpoint

All basic arithmetic now passes through one calculation function instead of being scattered across button handlers.