Calculator with Method Chaining - Problem
Design a Calculator Class with Method Chaining

Your task is to create a Calculator class that supports method chaining for performing consecutive mathematical operations. This is a classic example of the Fluent Interface design pattern, commonly used in modern programming.

The calculator should:
• Accept an initial value in the constructor
• Support basic operations: add, subtract, multiply, divide, and power
• Allow chaining operations like calc.add(5).multiply(3).subtract(2)
• Provide a getResult() method to retrieve the final value
• Handle division by zero with proper error handling

Example:
let calc = new Calculator(10);
calc.add(5).multiply(2).subtract(10).getResult(); // Returns 20

This pattern is widely used in libraries like jQuery, Lodash, and many SQL query builders!

Input & Output

example_1.js — Basic Chaining
$ Input: const calc = new Calculator(10); calc.add(5).multiply(2).getResult();
Output: 30
💡 Note: Starting with 10, add 5 to get 15, then multiply by 2 to get 30
example_2.js — Complex Operations
$ Input: const calc = new Calculator(2); calc.power(3).subtract(3).divide(5).getResult();
Output: 1
💡 Note: 2^3 = 8, subtract 3 to get 5, divide by 5 to get 1
example_3.js — Division by Zero
$ Input: const calc = new Calculator(10); calc.divide(0);
Output: Error: Division by zero is not allowed
💡 Note: Division by zero throws an error as required

Constraints

  • Initial value can be any real number
  • Operation values can be any real number
  • Division by zero must throw an error
  • Results within 10-5 of expected are considered correct
  • All methods except getResult() must return the Calculator instance

Visualization

Tap to expand
INPUT10ADD STATION+5Result: 15returns thisMULTIPLY×2Result: 30returns thisSUBTRACT-10Result: 20returns thisOUTPUT20Calculator Method Chaining - Assembly LineEach operation transforms the value and returns 'this' for seamless chaining
Understanding the Visualization
1
Raw Material
Initial value enters the assembly line
2
Addition Station
Adds specified value and passes result forward
3
Multiplication Station
Multiplies by specified value and continues the line
4
Final Product
GetResult() extracts the finished product from the line
Key Takeaway
🎯 Key Insight: Method chaining works by returning the same object instance ('this') from each method, allowing the next method to be called immediately without breaking the chain.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen