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

How do you extend sum to support add and subtract?

The answer

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.

More FAQs in sum(1)(2)(3) with Add and Subtract Operations

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.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Your learning library

Small steps. Big possibilities.

Find your next course. Build something great.

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.