Facebook Pixel

How would you convert the sum function to a generic curry?

Use the generic curry function: function curry(fn) { return function curried(...args) { if (args.length >= fn.length) return fn(...args); return (...next) => curried(...args, ...next); }; }. Then const sum = curry((a, b) => a + b).

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in sum(1)(2)(3) Variations and Follow-Up Questions

Use rest parameters: function sum(...args) { const total = args.reduce((a, b) => a + b, 0); return function(b) { if (b !== undefined) return sum(total + b); return total; }; }.

function sum(n) { const fn = m => sum(n + m); fn.toString = () => n; return fn; }. When JavaScript needs a primitive (like +0 or console.log), it calls toString and returns the accumulated sum.

How would you support multiple arguments (rest params), add other operations (multiply, subtract), make it a generic curry function, and what is the time/space complexity.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

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
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.