Understanding Currying in Javascript

Understanding Currying in Javascript

Currying is a technique of transforming a funaction that takes multiple arguments into a sequence of functions that each take one argument. Currying is a function transformation that makes function(a, b, c) callable as function(a)(b)(c).
It makes functions modular and reusable by breaking down a multi-argument function into smaller and single argument functions.

Example:
function add(a, b, c) { return a + b + c; } add(1)(2)(3); // returns 6

Implementing Currying in JavaScript

To implement currying, you can write a higher-order function that returns nested functions until all arguments are provided. This approach handles multiple and partial argument calls seamlessly! Here’s how you can implement a simple curry function:

function curry(func) {

return function curried(...args) {

if (args.length >= func.length) { return func(...args); }

else { return function(...moreArgs) { return curried(...args, ...moreArgs);

}; } }; }

// const join = (a, b, c) => { return ${a}_${b}_${c}; };

const curriedAdd = curry(join);

console.log(curriedJoin(1)(2, 3)); // Output: '1_2_3'

console.log(curriedJoin(1, 2)(3)); // Output: '1_2_3'

Explanation

  1. curriedJoin(1)(2, 3):
  • args = [1] → insufficient arguments.

  • Returns a new function that collects more arguments.

  • On the next call, args = [1, 2, 3] → sufficient arguments.

  • Executes join(1, 2, 3) → returns '1_2_3'.

  1. curriedJoin(1, 2)(3):

    • args = [1, 2] → insufficient arguments.

    • Returns a new function that collects more arguments.

    • On the next call, args = [1, 2, 3] → sufficient arguments.

    • Executes join(1, 2, 3) → returns '1_2_3'.

Example of Infinite Currying

Infinite currying is a technique where a function keeps returning itself until no arguments are passed. When no arguments are passed, the function returns the result. Consider a function that adds numbers indefinitely until no arguments are passed, at which point it returns the accumulated sum.

Here's how you can implement it:

function add(a) {

return function(b) {

if (b !== undefined) { return add(a + b); }

else { return a; }

}; }

Usage example:

console.log(add(1)(2)(3)(4)()); // Output: 10

console.log(add(5)(10)(15)()); // Output: 30

Explanation

  1. Recursive Function: The add function returns an inner function that expects a single argument b.

  2. Check Argument: Inside the inner function, it checks if b is defined.

    • If b is defined, it calls add again, adding b to the current accumulated value.

    • If b is undefined (no argument passed), it returns the accumulated value a.

  3. Termination: The function terminates and returns the accumulated result when it’s called with () at the end, triggering the return of the final accumulated sum.