currying

Currying is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c).

  • we can transform a function with multiple arguments into a sequence of nesting functions.

  • It returns a new function that expects the next argument inline.

  • It keeps returning a new function (that expects the current argument, like we said earlier) until all the arguments are exhausted.

  • The arguments are kept "alive"(via closure) and all are used in execution when the final function in the currying chain is returned and executed.

function curry(f) { // curry(f) does the currying transform
  return function(a) {
    return function(b) {
      return f(a, b);
    };
  };
}

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

let carriedSum = curry(sum);

carriedSum(1)(2); // 3

Example Description:

  • The result of curry(func) is a wrapper function(a).

  • When it is called like carriedSum(1), the argument is saved in the Lexical Environment, and a new wrapper is returned function(b).

  • Then carriedSum(1)(2) finally calls function(b) providing 2, and it passes the call to the original multi-argument sum.

Advanced currying:

function addCurry(x) {
  return function innrFn(y) {
    if (y !== undefined) {
      x += y;
      return innrFn;
    } else {
      return x;
    }
  }
}

addCurry(1)(2) // [Function: innrFn]
addCurry(1)(2)(); // 3
addCurry(1)(2)(3)(); // 6
  • when the function call is completed with argument will return the function.

  • when function is call is completed without argument will return the sum of all arguments.

Last updated