Easy
Design a Calculator
class. The class should provide the mathematical operations of addition, subtraction, multiplication, division, and exponentiation. It should also allow consecutive operations to be performed using method chaining. The Calculator
class constructor should accept a number which serves as the initial value of result
.
Your Calculator
class should have the following methods:
add
- This method adds the given number value
to the result
and returns the updated Calculator
.subtract
- This method subtracts the given number value
from the result
and returns the updated Calculator
.multiply
- This method multiplies the result
by the given number value
and returns the updated Calculator
.divide
- This method divides the result
by the given number value
and returns the updated Calculator
. If the passed value is 0
, an error "Division by zero is not allowed"
should be thrown.power
- This method raises the result
to the power of the given number value
and returns the updated Calculator
.getResult
- This method returns the result
.10⁻⁵
of the actual result are considered correct.設計一個Calculator
類別。
此類別應提供加、減、乘、除和求冪的數學運算。它允許使用方法鍊執行連續操作。 Calculator
類別建構函式應該接受一個數字作為result
的初始值。
Calculator
類別應該具有以下方法:
add
-value
加到result
中,並回傳更新後的Calculator
。subtract
-result
中減去給定的數字value
,並回傳更新後的Calculator
。multiply
-result
乘以給定數字value
,並回傳更新後的Calculator
。divide
-result
除以給定數字value
,並回傳更新後的Calculator
。0
,則應拋出錯誤"Division by zero is not allowed"
。power
-result
計算為給定數字value
的冪,並回傳更新後的Calculator
。getResult
- 此方法回傳result
。class Calculator{
//建構函式 初始化屬性result=參數的val值
constructor(val){ this.result = val;}
//加法
add(val){
this.result += val;
return this;
}
//減法
subtract(val){
this.result -= val;
return this;
}
//乘法
multiply(val){
this.result *= val;
return this;
}
//除法
divide(val){
if (val == 0){
throw new Error(
"Division by zero is not allowed"
)}
this.result /= val;
return this;
}
//指數運算(幂)
power(val){
this.result **= val;
return this;
}
//取得結果
getResult(val){
return this.result;
}
}
const cal = new Calculator(10);
let ans = cal.add(5).subtract(7).getResult();
console.log(`[Test1] ${ans}`);
//Output: 8
const cal2 = new Calculator(2);
ans = cal2.multiply(5).power(2).getResult();
console.log(`[Test2] ${ans}`);
//Output: 100
const cal3 = new Calculator(20);
ans = cal3.divide(0).getResult();
console.log(`[Test3] ${ans}`);
//Output: Uncaught Error Error: Division by zero is not allowed