-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path2726-calculator-with-method-chaining.js
89 lines (82 loc) · 2.21 KB
/
2726-calculator-with-method-chaining.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* 2726. Calculator with Method Chaining
* https://leetcode.com/problems/calculator-with-method-chaining/
* Difficulty: 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.
*
* Solutions within 10-5 of the actual result are considered correct.
*/
class Calculator {
/**
* @param {number} value
*/
constructor(value) {
this.value = value;
}
/**
* @param {number} value
* @return {Calculator}
*/
add(value) {
this.value += value;
return this;
}
/**
* @param {number} value
* @return {Calculator}
*/
subtract(value) {
this.value -= value;
return this;
}
/**
* @param {number} value
* @return {Calculator}
*/
multiply(value) {
this.value *= value;
return this;
}
/**
* @param {number} value
* @return {Calculator}
*/
divide(value) {
if (value === 0) {
throw new Error('Division by zero is not allowed');
}
this.value /= value;
return this;
}
/**
* @param {number} value
* @return {Calculator}
*/
power(value) {
this.value **= value;
return this;
}
/**
* @return {number}
*/
getResult() {
return this.value;
}
}