Submission link - https://bigfrontend.dev/problem/implement-curry/discuss/765
/**
* @param { Function } func
*/
function curry(func) {
// we need to return a function to make it curry-able.
return function curried(...args) {
// if the passed arguments are greater than original function 'func' parameters
// then we directly call `func` with passed arguments
if(args.length >= func.length) {
return func.apply(this, args);
} else {
// else we gather 2nd argument and pass it to `curried` function.
// this will continue till arguments >= parameters
return function next(...args2) {
return curried.apply(this, args.concat(args2));
}
}
}
}
I tried to attempt it but couldn't get actual logic. Such problems look simple but you learn a lot when you pay attention to details.
Example - I realized that apply
and bind
methods are powerful. I had to understand that why did few people use bind
over apply
.
In the apply
method, you need to pass arguments all at once. In the bind
, you can reserve them and when next time that function gets called, it will apply
those arguments too.
- We create a function called
curried
that we return to take arguments - We check if given arguments
args
>= functionfunc
parameters or not - If the above condition is
true
then we callfunc
with all arguments we received - Else we return a new function which takes the next argument and call the
curried
function recursively
- To make a function curry-able, we return a function
curried
- The
curried
will take argumentsargs
- We will check if
args.length
(passed arguments) >=func.length
(total parameters)- If the above condition is
true
then we directly callfunc
with passed arguments - Else we will return another function (because few arguments are still pending) to collect the next arguments
- If the above condition is
- We will take those next arguments and recursively call
curried
function until main conditionargs.length
(passed arguments) >=func.length
is true
I'm excited to improve the solution and code walkthrough. Feel free to drop a comment, or send a PR or send memes @knowkalpesh.