One Pager Cheat Sheet
Currying is a transformation of functions that translates a function from callable as
f(a, b, c)into a sequence of callable functions as
f(a)(b)(c), which helps to avoid passing the same variable multiple times and create higher order functions.
- We are creating a function called
curry
that will return another function,curriedFunc
, that will either spread the arguments provided or recursively call itself, depending on the case.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
16
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);
};
}
};
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
You're doing a wonderful job. Keep going!
If you had any problems with this tutorial, check out the main forum thread here.