π Frontend DSA 8 - π Currying in JavaScript: Define a Chainable Sum Function Without Final ()
JavaScript offers powerful flexibility when it comes to function chaining, currying, and type coercion. In this guide, we'll implement a function sum() that can be called repeatedly like this:
sum(0)(1)(2)(3)(4)(5) β 15Notice: No final () required! π€―
β Problem Statement
Write a function such that:
console.log("" + sum(0)(1)(2)(3)(4)(5)); // 15It should:
- Allow infinite currying via
sum(x)(y)... - Return the final result without an extra
() - Rely on implicit coercion using
toString()orvalueOf()
π» Final Working Code
function sum(x) {
// Total will store the accumulating sum
let total = x || 0;
// Recursive function to chain more additions
function next(y) {
total += y || 0; // Add next value
return next; // Return itself for further chaining
}
// Override toString for final coercion when logged or used as string
next.toString = function () {
return total;
};
return next;
}
// π Test cases
console.log("" + sum(0)(1)(2)(3)(4)(5)); // 15
console.log("" + sum(5)(10)(-2)); // 13
console.log("" + sum(100)); // 100Problem Statement
π How It Works
π§ Key Concepts:
- Closure:
totalis preserved across chained calls. - Function returning itself:
next()returnsnext, enabling further chaining. - Coercion with
.toString(): JavaScript converts the function into a primitive value usingtoString()when used in a string context (likeconsole.log("" + fn)).
β οΈ JavaScript Insight
If you used:
console.log(sum(1)(2)(3)); // β Outputs [Function: next]Thatβs because you're not coercing it to string/number.
β Fix:
Use coercion explicitly:
console.log(+sum(1)(2)(3)); // 6
console.log("" + sum(5)(6)); // 11You can also implement valueOf:
next.valueOf = () => total;Then:
console.log(+sum(1)(2)(3)); // 6π§ͺ Additional Test Cases
console.log("" + sum()); // 0
console.log("" + sum(0)(0)(0)); // 0
console.log("" + sum(10)(20)(30)); // 60
console.log("" + sum(-5)(-10)(25)); // 10β‘ Bonus: Arrow Function Version
const sum = x => {
let total = x || 0;
const next = y => (total += y || 0, next);
next.toString = () => total;
return next;
};
console.log("" + sum(1)(2)(3)); // 6Code Block
π‘ When to Use This Pattern?
β For:
- Chainable APIs
- Custom fluent interfaces
- Logging or debugging DSLs
β Not for:
- Production-critical arithmetic (due to coercion reliance)
Hey there from LearnYard! π
Glad to see you exploring the free content from our course! Weβve shared 10 valuable articles at no cost to help you get a real feel of whatβs inside.
If youβve found these helpful, weβd love to know! π¬
Share your thoughts or key takeaways on LinkedIn, Twitter, or Instagram β and donβt forget to tag Gourav Hammad & Mohammad Fraz. Weβll personally respond to your post!
Thanks for being part of the LearnYard journey. Keep learning, keep growing! π
Loved the free content? Want access to the full course β for free? πΈ
Share the course with your friends using your affiliate link (youβll find it on your profile or home page), and earn 20% commission on each sale.
Just 4β5 sales and youβll recover the full course price of your course π
So why wait? Start sharing, start earning, and unlock the rest of the course effortlessly! π οΈπ
π Keywords for SEO
- JavaScript Currying Without Final Call
- Chainable Function Using
toStringin JavaScript - Implement
sum(1)(2)...Without Final()in JavaScript - Currying and Overriding
toString()in JavaScript - Function Chaining with Coercion in JavaScript
- JavaScript Implicit Type Conversion in Functions
- How to Use
valueOfandtoStringfor Currying - Override Coercion Methods in JavaScript Functions
- JavaScript Lazy Evaluation with Coercion
- Smart Function Chaining Techniques in JavaScript
π’ Hashtags for Visibility
#JavaScriptCurrying #ChainableFunctions #ToStringOverride #JavaScriptTips
#FunctionCoercionJS #LazyEvaluation #JSAdvancedConcepts #LearnJavaScript
#FrontendMasters #CodeNewbie #JSInterviewPrep #FunctionalProgrammingJS
#JSChainingWithoutCall #SmartJS #ValueOfToStringHack #JSClosures
#AdvancedJavaScript #JavaScriptDeepDive #TechLearning #FrontendDevelopment