Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 23, 2021 07:54 am GMT

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             }            }         }

Example

Well 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);    };  };}// usagefunction sum(a, b) {  return a + b;}let curriedSum = curry(sum);alert( curriedSum(1)(2) ); // 3

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 libraryalert( curriedSum(1, 2) ); // 3, still callable normallyalert( curriedSum(1)(2) ); // 3, called partially

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;            }   }}
let orderItem298 = checkStock('FN9382')('SOUTH')(3); // FN9382 from SOUTH is reduced by 3

Original Link: https://dev.to/malapashish/what-is-currying-2jea

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To