Solution
Our solution would be implementing the function curry()
that will accept one parameter (a function) as an argument.
In this method we are going to return another function called curriedFunc()
that will gather the arguments in an array, and this function itself will return another function depending on the case.
1function curry(func) {
2 return function curriedFunc(...args) { }
3}
First, we are going to check if the number of args
provided equal the number of the args that the function expects, and if so, we are going to spread the args elements and pass them into a function.
1if (args.length >= func.length) {
2 return func(...args);
3}
If the number of args provided does not equal the expected number, we are going to return a function that collects the next arguments and recursively calls curriedFunc()
, passing it those next arguments.
1else {
2 return function (...next) {
3 return curriedFunc(...args, ...next);
4 };
5}
This being said, our final solution would look like the following:
1function curry(func) {
2 // ...args collects arguments as array
3 return function curriedFunc(...args) {
4 // Check if current args passed equals the number of args func expects
5 if (args.length >= func.length) {
6 // if args length equals the expected number, pass into func (spread)
7 return func(...args);
8 } else {
9 /* Else, we return a function that collects the next arguments passed and
10 recursively call curriedFunc */
11 return function (...next) {
12 return curriedFunc(...args, ...next);
13 };
14 }
15 };
16}
xxxxxxxxxx
function curry(func) {
// ...args collects arguments as array
return function curriedFunc(args) {
// Check if current args passed equals the number of args func expects
if (args.length >= func.length) {
// if args length equals the expected number, pass into func (spread)
return func(args);
} else {
/* Else, we return a function that collects the next arguments passed and
recursively call curriedFunc */
return function (next) {
return curriedFunc(args, next);
};
}
};
}