BFE 1. Implement curry()
What is currying?
Currying is a functional programming technique that allows me to partcially apply a function by breaking down the parameters into a series of functions that each function takes some of the parameters.
Example
add(1, 2, 3) -> add(1)(2)(3)
add(1, 2, 3) -> add(1, 2)(3)
add(1, 2, 3) -> add(1)(2, 3)
Thoughts:
Need to return a function for chaining the calls until all the arguments are provided.
Tips:
-
Function.prototype.length:
get the number of parameters of a function.
-
Function.prototype.apply:
call a function with a given this value and arguments provided as an array.
-
Function.prototype.concat:
merge two or more arrays.
Code:
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
} else {
return function (...nextArgs) {
return curried.apply(this, args.concat(nextArgs));
};
}
};
}
Reference
Copyright © 2024 | All rights reserved.