Skip to main content

Recursion / Function

๐Ÿš€ Frontend DSA 9 - ๐Ÿง  JavaScript Currying: Flexible Argument Pattern for Sum Function

Currying is a functional programming technique where a function of multiple arguments is transformed into a sequence of unary functions.

This article explores a more advanced, flexible curry function that:

  • Allows partial application of arguments
  • Works for any calling pattern
  • Returns the final result only when sufficient arguments are provided

๐ŸŽฏ Problem Statement

Make a curried version of a function like this:

function sum(a, b, c) {
  return a + b + c;
}

โœ… Should support:

curriedSum(1, 2, 3)   โžž 6
curriedSum(1)(2, 3)   โžž 6
curriedSum(1)(2)(3)   โžž 6

โœ… Final Working Code

function curry(fun) {
    return function myCurried(...args) {
        // If enough args collected, invoke original function
        if (args.length >= fun.length) {
            return fun.apply(this, args);
        } else {
            // Otherwise, return a function that gathers more args
            return function(...args2) {
                return myCurried.apply(this, args.concat(args2));
            };
        }
    }
}

function sum(a, b, c) {
  return a + b + c;
}

let curriedSum = curry(sum);

// ๐Ÿ” Test cases
console.log(curriedSum(1, 2, 3));   // 6
console.log(curriedSum(1)(2, 3));   // 6
console.log(curriedSum(1)(2)(3));   // 6

Problem Statement


๐Ÿ” How It Works

Step-by-step:

  1. curry() wraps the original function.
  2. If enough arguments (args.length >= fun.length) are provided, it executes fun with those arguments.
  3. If not, it returns a new function that collects additional arguments.
  4. The recursion continues until all required arguments are gathered.

๐Ÿ” Real Use Case Example

Imagine you have a multiply(a, b, c) function. With this curry() helper, you can call:

const multiply = (a, b, c) => a * b * c;
const curriedMultiply = curry(multiply);

console.log(curriedMultiply(2, 3, 4)); // 24
console.log(curriedMultiply(2)(3)(4)); // 24
console.log(curriedMultiply(2)(3, 4)); // 24

This is super useful in functional programming, middleware, or React hooks, where partial application is helpful.


๐Ÿง  JavaScript Insight

  • fun.length gives the number of expected arguments (function arity).
  • args.concat(args2) builds the full list of arguments progressively.
  • apply() is used to call the function with a dynamic array of arguments.

๐Ÿงช More Test Cases

function logThree(a, b, c) {
  return `${a}-${b}-${c}`;
}

let curriedLog = curry(logThree);

console.log(curriedLog("X", "Y", "Z"));  // X-Y-Z
console.log(curriedLog("X")("Y", "Z"));  // X-Y-Z
console.log(curriedLog("X")("Y")("Z"));  // X-Y-Z

Code Block


๐Ÿš€ Bonus Tip: Dynamic Arity Currying?

This current curry() relies on knowing the functionโ€™s length. If you want to curry variadic functions, thatโ€™s more complex and would need custom termination logic (e.g., .exec() or .value() at the end).


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 Flexible Currying Function
  • Curry with Multiple Argument Calls in JavaScript
  • Curry Function Supporting sum(1)(2, 3) Pattern
  • JavaScript Curry Recursion with apply()
  • Advanced Currying Patterns in JavaScript
  • Partial Application with Currying in JS
  • How to Handle Variable Arguments in Currying
  • Recursive Curry Function in JavaScript
  • Smart Currying with Dynamic Arity
  • JavaScript Currying for Real-World Use Cases

๐Ÿ“ข Hashtags for Visibility

#JavaScriptCurrying #FlexibleCurrying #AdvancedJS #FunctionComposition
#JavaScriptTips #MultipleArgumentsJS #CurryWithApply #JSClosures
#FunctionalProgrammingJS #CodeNewbie #FrontendMasters #JSDeepDive
#PartialApplication #LearnJavaScript #CurryingTechniques #SmartFunctions
#JSInterviewPrep #FrontendDevelopment #TechLearning #JSChainingPatterns