Curry a function
You know one argument now and the rest later. A tax rate is fixed, but the price
arrives from the cart. You could write a fresh wrapper for every case —
(price) => add(tax, price) — or you could call the function one argument at a
time and let each call hold what it was given.
That pattern is called currying: a function of several arguments becomes a
chain of one-argument functions. add(1, 2, 3) becomes add(1)(2)(3). Each call
collects one argument until the original has enough to run.
The rule for "enough" is the function's arity — how many parameters it
declares, read from fn.length. Collect fewer than that and you hand back another
one-argument function; reach it and you finally call the original:
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
}
return (...rest) => curried(...args, ...rest);
};
}
curried gathers arguments in args. While there are too few, it returns a new
function that appends the next argument and tries again — that is the chain. Once
args.length reaches fn.length, fn has everything, so it runs and the chain
ends with the result. add(10) therefore stays a function, while add(10)(5)(1)
returns 16.
Export curry from index.js. Your job is to turn a function of any arity into
a chain of one-argument calls.
Challenge
You want to fix one argument now and supply the rest later, without writing a
fresh wrapper each time. Export a curry function from index.js to call a
function one argument at a time.
curry takes a function of any number of arguments and returns a chain of
one-argument functions, so curry(fn)(a)(b)(c) calls fn(a, b, c). While the
chain holds fewer arguments than the original declares, it returns another
function; once it has enough, it runs the original and returns its result. A
partially applied function must not run the original.