Facebook Pixel

sum(1)(2)(3) with Add and Subtract Operations

Extending the sum function to support multiple operations.

sum(1)(2)(3) with Add and Subtract Operations

Extended Version

function calc(a) { return { add: function (b) { return calc(a + b); }, subtract: function (b) { return calc(a - b); }, multiply: function (b) { return calc(a * b); }, result: function () { return a; }, }; } calc(5).add(3).subtract(2).result(); // 6

How It Works

Each method returns a new calc object with the updated value. The result method returns the final value.

Chain Pattern

calc(10) .add(5) // 15 .subtract(3) // 12 .multiply(2) // 24 .result(); // 24

The Takeaway

Extended sum: return an object with methods (add, subtract, multiply, result). Each method returns a new calc object with the updated value. This is the chain pattern (like jQuery, lodash). The result method terminates and returns the value.

Return an object with methods: function calc(a) { return { add: b => calc(a + b), subtract: b => calc(a - b), result: () => a }; }. Each method returns a new calc with the updated value. result() returns the final value.

The chain pattern (also called fluent interface or method chaining). Each method returns a new object with the updated value, allowing methods to be chained: calc(5).add(3).subtract(2).result(). Similar to jQuery and lodash.

Call the result() method: calc(5).add(3).result() returns 8. The result method returns the accumulated value and terminates the chain.

Yes. calc(10).add(5).subtract(3).multiply(2).result() returns 24. Each method returns a new calc with the updated value, so you can chain any combination of operations.

Each method closes over the current value (a). add returns calc(a + b), which creates a new calc with the new value. The closure keeps the value alive between chained calls.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.