- Lodash supports the creation of curried function by using _.curry() method.
- A normal function when called with appropriate number of parameters it runs to the end of the execution.
- Sometime while programming we face situation when we don’t have sufficient number of parameters to call a function.I mean think of a situation when a method needs 2 parameters param1 and param2 But at present we have only param1 value is available and param2 will be available in the coming future.This type of situation can be easily handled by currying function.
- A curried function is only called underneath real function only if all the input parameter is passed or else it returns a partial function which can be used later part of the program when the other parameters are available.
- In this demo, “We will learn to use the lodash provided curry function”.
- The following code contains a method addTwoNumber().This function is curried using Lodash and saved the curried version in curriedAddTwoNumber1.Then 1st parameter 5 is passed to curriedAddTwoNumber1 which return a partial function curriedAddTwoNumber2 as only 1 parameter is passed.Then in the later stage the 2nd parameter 6 is passed.Now both the parameters are passed it prints the result 11.
<!DOCTYPE html> <html> <head> <script src="https://rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <script> //function to add two numbers var addTwoNumber = function(num1, num2) { return num1 + num2; }; //function is curreied using lodash var curriedAddTwoNumber1 = _.curry(addTwoNumber); //1st argument passed here var curriedAddTwoNumber2 = curriedAddTwoNumber1(5); //2nd argument passed here var result = curriedAddTwoNumber2(6); console.log("result: " + result); </script> </body> </html>
- The output of the following code can be found in below JSBIN link.