Currying
What does currying do?
It curries the function 😀👍
/**
* Currying in TypeScript
* @param func {Function} Function to be curried
* @returns A new function that wraps the given function
*/
function curry(func: Function) {
return function curried(...args: any[]) {
if (args.length >= func.length) {
return func.apply(this, args);
} else {
return function(...args2: any[]) {
return curried.apply(this, args.concat(args2));
}
}
}
};
How does it work?
function curry(func: Function): This line declares a function named
currythat takes in a single parameter func which is aFunction.return function curried(...args: any[]): This line returns an anonymous function that is assigned the name
curriedand takes in a rest parameterargswhich is an array of elements of typeany.if (args.length >= func.length): This line checks if the length of the
argsarray is greater than or equal to the length of thefuncfunction.return func.apply(this, args): If the length of
argsis greater than or equal to the length offunc, this line calls theapply()method onfunc, passing inthisandargsas arguments, and returns theresult.return function(...args2: any[]): This line returns an anonymous function that takes in a rest parameter
args2which is an array of elements of typeany.return curried.apply(this, args.concat(args2)): This line calls the
apply()method on thecurriedfunction, passing in this and the result of concatenatingargsandargs2as arguments, and returns theresult.
Overall, the curry function takes in a function as an argument and returns a curried version of that function. A curried function is a function that takes in one or more arguments and returns a new function until all of the arguments have been provided, at which point the original function is called with all of the arguments.