curry
As you might already know, a simple definition of curried function
is a function with multiple arguments that is able to take each argument at any time.
For example, assume that there is a function named sum
with three arguments:
const sum = (a, b, c) => a + b + c;
console.log(sum(1, 2, 3)); // output> 3
This function works perfectly, but it must take all of its arguments at the same time.
In order to pass the arguments at any time that we want, we can use curry
function to convert any kind of functions to curried function
Curried version of sum
:
const curriedSum = curry(sum);
console.log(curriedSum(1, 2, 3)) // output> 3
console.log(curriedSum(1, 2)(3)) // output> 3
console.log(curriedSum(1)(2, 3)) // output> 3
console.log(curriedSum(1)(2)(3)) // output> 3
With a curried function
you can pass any number of arguments at any time.
But in order to use curry
function there are some rules that you should keep in mind.
- If the function that you pass to the
curry
has default values for its parameters, thecurry
function doesn't work as expected, because it has to count the number function's arguments (a parameter with default value doesn't count).
// This function shouldn't be sent to the `curry` function
const sum = (a, b = 2, c = 3) => a + b + c;
The order of the arguments is important. Sending the arguments at any time doesn't mean that we can send them in any order. You can't expect to recieve arg
c
beforeb
.The body of function only runs when all of its arguments be passed.
Almost all of the functions in
composable-utils
library arecurried function
.