{ "data": { "question": { "questionId": "2863", "questionFrontendId": "2726", "boundTopicId": null, "title": "Calculator with Method Chaining", "titleSlug": "calculator-with-method-chaining", "content": "
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.
\n
Example 1:
\n\n\nInput: \nactions = ["Calculator", "add", "subtract", "getResult"], \nvalues = [10, 5, 7]\nOutput: 8\nExplanation: \nnew Calculator(10).add(5).subtract(7).getResult() // 10 + 5 - 7 = 8\n\n\n
Example 2:
\n\n\nInput: \nactions = ["Calculator", "multiply", "power", "getResult"], \nvalues = [2, 5, 2]\nOutput: 100\nExplanation: \nnew Calculator(2).multiply(5).power(2).getResult() // (2 * 5) ^ 2 = 100\n\n\n
Example 3:
\n\n\nInput: \nactions = ["Calculator", "divide", "getResult"], \nvalues = [20, 0]\nOutput: "Division by zero is not allowed"\nExplanation: \nnew Calculator(20).divide(0).getResult() // 20 / 0 \n\nThe error should be thrown because we cannot divide by zero.\n\n\n
\n
Constraints:
\n\nactions
is a valid JSON array of stringsvalues
is a valid JSON array of numbers2 <= actions.length <= 2 * 104
1 <= values.length <= 2 * 104 - 1
actions[i]
is one of "Calculator", "add", "subtract", "multiply", "divide", "power", and "getResult"Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES6 features.
lodash.js library is included by default.
\\r\\n\\r\\nFor Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.
\"], \"typescript\": [\"Typescript\", \"TypeScript 5.1.6, Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES2022 features.
lodash.js library is included by default.
\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }