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:
add adds the given number value to result and returns the updated Calculator object.subtract subtracts the given number value from result and returns the updated Calculator object.multiply multiplies result by the given number value and returns the updated Calculator object.divide divides result by the given number value and returns the updated Calculator object. If the given value is 0, it throws an error "Division by zero is not allowed".power raises result to the power of the given number value, i.e., result = result ^ value. After the calculation, it returns the updated Calculator object.getResult returns the value of result.// 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
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;
}
}