AniUI Academy

Partial application, left and right

mediumFunctions & Closures+250 XPPractice

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. partial puts them on the left; partialRight on 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 accumulate
const 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 right

partialRight is handy when the trailing argument is the stable one (an options bag, a divisor).

What it has to do

  • partial places the preset arguments before the call-time arguments.
  • partialRight places 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 this when used as an object method.

Notes

  • Use preset.concat(later), not preset.push(...later) — mutating preset is what makes two calls to the same partial start sharing arguments.
  • Partial application is strictly weaker than currying: it does not wait for fn.length and will happily call fn short. Pick the one that matches how you want the caller to drive it.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.