Calculator with Method Chaining - Problem
Design a Calculator Class with Method Chaining
Your task is to create a
The calculator should:
• Accept an initial value in the constructor
• Support basic operations:
• Allow chaining operations like
• Provide a
• Handle division by zero with proper error handling
Example:
This pattern is widely used in libraries like jQuery, Lodash, and many SQL query builders!
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 20This 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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code