Create reusable partial functions
Build specialized functions by pre-supplying some arguments.
JS Puzzles · Const
Currying transforms a multi-argument function so it can be called through successive calls such as f(a)(b)(c). The wrapper collects arguments and invokes the original function when enough have been supplied.
Currying transforms a function that accepts several arguments together into one that can receive them through successive calls. A wrapper stores previously received arguments and invokes the original function once the required count is available.
curry(func)| Name | Type | Description |
|---|---|---|
func | Function | The function to transform into a curried callable. |
A wrapper function that accepts arguments incrementally and calls the original function after receiving enough arguments.
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn(...args);
return (...next) => curried(...args, ...next);
};
}
const sum3 = (a, b, c) => a + b + c;
const curriedSum3 = curry(sum3);
console.log(curriedSum3(1)(2)(3));
console.log(curriedSum3(1, 2)(3));This implementation collects arguments until it has enough to invoke the original function, supporting both chained and mixed calls.
Build specialized functions by pre-supplying some arguments.
Compose data-processing or configuration pipelines.
Adapt APIs that provide values one at a time.
partial applicationclosureslexical environment_.curry