Topic Description

Design a Calculator class that includes mathematical operations such as add, subtract, multiply, divide, and power. The class should also support method chaining for continuous operations. The constructor of the Calculator class will accept a number to serve as the initial value of result.

Specifically, the Calculator class should include the following methods:

// Example 1:
Input: actions = ["Calculator", "add", "subtract", "getResult"],
values = [10, 5, 7]
Output: 8
Explanation:
new Calculator(10).add(5).subtract(7).getResult() // 10 + 5 - 7 = 8

// Example 2:
Input: actions = ["Calculator", "multiply", "power", "getResult"],
values = [2, 5, 2]
Output: 100
Explanation:
new Calculator(2).multiply(5).power(2).getResult() // (2 * 5) ^ 2 = 100

Answer

function Calculator(initVal) {
    this.value = initVal
};

Calculator.prototype.add = function(val){
	this.value += val
	return this
}

Calculator.prototype.subtract = function(val){
	this.value -= val
	return this
}

Calculator.prototype.multiply = function(val){
	this.value *= val
	return this
}

Calculator.prototype.divide = function(val){
	if(val==0){
		throw new Error("Division by zero is not allowed");
	}
	this.value /= val
	return this
}

Calculator.prototype.power = function(val){
	this.value = Math.pow(this.value, val);
	return this
}

Calculator.prototype.getResult = function(){
	return this.value;
}
class Calculator {
  constructor(value) {
    this.value = value;
  }

  add(value) {
    this.value += value;
    return this;
  }

  subtract(value) {
    this.value -= value;
    return this;
  }

  multiply(value) {
    this.value *= value;
    return this;
  }

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

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

  getResult() {
    return this.value;
  }
}