Create Curry Function (Medium)
Good evening! Here's our prompt for today.
In mathematics and computer science, currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each takes a single argument. Currying provides a way for working with functions that take multiple arguments, and using them in frameworks where functions might take only one argument.
In programming, currying is an advanced technique of working with functions. It’s used not only in JavaScript, but in other languages as well.
It is a transformation of functions that translates a function from callable as f(a, b, c)
into callable as f(a)(b)(c)
. Currying doesn’t call a function. It just transforms it.
Currying is a very useful technique because it helps to avoid passing the same variable again and again, but it also helps to create a higher order function.
Currying transforms a function with multiple arguments into a sequence/series of functions each taking a single argument.
Your task would be to implement a curry()
function, which accepts a function and return a curried one.
For example:
Here is an example
1const joinArgs = (a, b, c) => {
2 return `${a}_${b}_${c}`
3}
4
5const curriedFunc = curry(joinArgs)
6
7curriedJoin(1, 2, 3) // '1_2_3'
8curriedJoin(1)(2, 3) // '1_2_3'
9curriedJoin(1, 2)(3) // '1_2_3'

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);
};
}
};
}