Tuesday, November 13, 2018

Understanding Currying in JavaScript

This tutorial explains how to create currying function in javascript.  Basically currying is the process of taking a function with multiple arguments and returning a series of functions that take one argument and eventually resolve to a value.
Or in another you can say,
Currying is the process of breaking down a function into a series of functions that each take a single argument.
Understanding Currying in JavaScript

Currying example :

Let’s look at a simple add function. It accepts three operands as arguments, and returns the sum of all three as the result.

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

console.log(add(1,2,3)) // output :- 6

Output:-
-------------
> 6

Lets see the currying version of add function, that behaves differently. It accepts one argument and returns one function. The returned function also accepts one argument and also returns another function that also accepts one argument and so on ... This cycle continues until the returned function accepts the last argument. The last one in the chain, finally returns the sum result.

function add(a) {
    return (b) => {
        return (c) => {
            return a + b + c
        }
    }
}
console.log(add(1)(2)(3)) // output :- 6

Output:-
-------------------
> 6

Currying Wrapper :

In this example we are using a wrapper function in place of the real function, we can create another function that generates this wrapper function. We’ll call this new function curry — a higher order function that returns a series of nested accumulator functions that invoke the callback function fn in the end. Lets see the wrapper version of currying function.
function curry(fn) {
  return (x) => {
    return (y) => {
      return (z) => {
        return fn(x, y, z);
      };
    };
  };
}
const sum = curry((x, y, z) => {
  return x + y + z;
});

console.log(sum(1)(2)(3))  // output :- 6  

Output:
-----------------------
> 6

This is all about currying function in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment