What is Currying?

malapashish

malapashish

Posted on May 23, 2021

What is Currying?

If you are present in the world of Javascript long enough then you would have come across a term known as ‘Currying’. Although this is an advanced technique understanding it is not that hard. We can define Currying as, a technique of evaluating function with multiple arguments, into sequence of functions with single argument. Confused ?. Good because while learning new concepts in programming confusion is your best friend.

In other words, when a function, instead of taking all arguments at one time, takes the first one and returns a new function that takes the second one and returns a new function which takes the third one, and so forth, until the last function returns the data that you want. In short, currying doesn't call a function , it just transforms it.

We will look at the syntex first

function Myfunction(a) {
        return (b) => {
           return (c) => {
             return a * b * c
             }
            }
         }
Enter fullscreen mode Exit fullscreen mode

Example

We’ll create a helper function curry(f) that performs currying for a two-argument f. In other words, curry(f) for two-argument f(a, b) translates it into a function that runs as f(a)(b).

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 curriedSum = curry(sum);

alert( curriedSum(1)(2) ); // 3
Enter fullscreen mode Exit fullscreen mode

More advanced implementations of currying, such as _.curry from lodash library, return a wrapper that allows a function to be called both normally and partially:

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

let curriedSum = _.curry(sum); // using _.curry from lodash library

alert( curriedSum(1, 2) ); // 3, still callable normally
alert( curriedSum(1)(2) ); // 3, called partially
Enter fullscreen mode Exit fullscreen mode

Advanced curry implementation

Your curried function may look something like this:

function checkStock(stockID){ 
   //some check code 
   if(err){throw err;} 

   return (warehouseID) => { 
      //some check code 
      if(err){throw err;}
      return(stockDeduct)=> { 
        //some check code         
        if(err){throw err;}
         return stockID 
                + ' from ' + warehouseID
                + ' is reduced by ' + stockDeduct;      
      }
   }
}
Enter fullscreen mode Exit fullscreen mode
let orderItem298 = checkStock('FN9382')('SOUTH')(3); // FN9382 from SOUTH is reduced by 3
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
malapashish
malapashish

Posted on May 23, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related