2726. Calculator with Method Chaining
Design a Calculator class that performs mathematical operations (addition, subtraction, multiplication, division, and exponentiation) using method chaining.
📄 Problem Statement
- Constructor: Accepts an initial number as the result.
add(value): Adds value and returns the calculator instance.subtract(value): Subtracts value and returns the calculator instance.multiply(value): Multiplies value and returns the calculator instance.divide(value): Divides by value and returns the calculator instance. Throws error if value is 0.power(value): Raises result to the power of value and returns the calculator instance.getResult(): Returns the final result.
✅ 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;
}
}