TobilobaCodes – LeetCode Explorer

2726. Calculator with Method Chaining

Design a Calculator class that performs mathematical operations (addition, subtraction, multiplication, division, and exponentiation) using method chaining.

📄 Problem Statement

✅ Solutions within 1e-5 of the actual result are considered correct.

💡 Example


const calc = new Calculator(10);
const result = calc.add(5).subtract(3).multiply(2).divide(3).power(2).getResult();

console.log(result); // Output: 64

🧠 Explanation

We implement each method in the Calculator class to update the internal result and return the current instance for chaining.

We throw an error in divide() if the passed value is zero to avoid invalid operations.

✅ Your Solution


class Calculator {
  constructor(value) {
    this.result = value;
  }

  add(num) {
    this.result += num;
    return this;
  }

  subtract(num) {
    this.result -= num;
    return this;
  }

  multiply(num) {
    this.result *= num;
    return this;
  }

  divide(num) {
    if (num === 0) throw new Error("Division by zero is not allowed");
    this.result /= num;
    return this;
  }

  power(num) {
    this.result = Math.pow(this.result, num);
    return this;
  }

  getResult() {
    return this.result;
  }
}