Currying takes your functions to a whole new level of flexibility and power!
Abdul Ghaffar
Senior Software Engineer @ Tkxel | Serverless | AWS | JavaScript | Typescript | Node.js | React.js | Vue.js | Angular | Electron | PHP | Laravel
Currying transforms a function that takes multiple arguments into a sequence of functions that each take a single argument. This can be useful for a number of reasons:
For example, consider the following function add that takes two arguments and returns their sum:
We can use currying to transform add into a series of functions that each take a single argument:
Now, instead of calling add with two arguments, we can call it with a single argument x, which returns a new function that takes an argument y. This new function can then be called to compute the sum of x and y.
领英推荐
Here is an example of how we can use the curried add function:
Lodash popular utility library includes a curry function that allows you to curry any function. i.e
Alternatively, you can use the curryRight function to curry the function from the right-hand side instead of the left. This can be useful if you want to fix the rightmost argument instead of the leftmost argument.
Currying can be useful for creating specialized versions of functions, or for making it easier to work with functions that take multiple arguments by allowing you to fix some arguments and only vary others.