Partial application, left and right
Partial application is what you actually reach for in product code: you have fetchJson(baseUrl, path, options) and you want fetchApi with the base URL already filled in. Unlike currying, it does not care about arity — it hands over whatever it has and calls through immediately.
Implement two functions. partial(fn, ...preset) returns a function that calls fn with the preset arguments first, followed by the arguments given at call time. partialRight(fn, ...preset) returns a function that calls fn with the call-time arguments first, followed by the preset arguments. Both return fn's return value, both work with no preset arguments at all, both can be called repeatedly without the preset arguments accumulating, and both preserve this so they can be used as object methods.
Arguments
fnFunction- The function to pre-fill.
...presetany[]- Arguments to lock in.
partialputs them on the left;partialRighton the right.
Returns
Function — A new function that calls fn with the preset and call-time arguments combined in order.
Examples
const greet = (greeting, name) => greeting + ", " + name;
const hi = partial(greet, "Hi");
hi("Ada"); // "Hi, Ada"
hi("Bob"); // "Hi, Bob" — reusable, preset does not accumulateconst divide = (a, b) => a / b;
const halve = partialRight(divide, 2);
halve(10); // 5
halve(4); // 2 — call-time arg goes on the left, preset on the rightpartialRight is handy when the trailing argument is the stable one (an options bag, a divisor).
What it has to do
partialplaces the preset arguments before the call-time arguments.partialRightplaces the preset arguments after the call-time arguments.- Both work when no preset arguments are supplied.
- Repeated calls to the same partial do not accumulate arguments.
- Both preserve
thiswhen used as an object method.
Notes
- Use
preset.concat(later), notpreset.push(...later)— mutatingpresetis what makes two calls to the same partial start sharing arguments. - Partial application is strictly weaker than currying: it does not wait for
fn.lengthand will happily callfnshort. Pick the one that matches how you want the caller to drive it.
Stuck? The javascript course covers everything this challenge needs.
- 1.presets the leading arguments
- 2.presets the trailing arguments
- 3.works with no preset arguments
- 4.a partial can be reused without accumulating
- 5.preserves this as a method
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.