AniUI Academy

Compose functions right to left

mediumFunctions & Closures+250 XPPractice

compose(f, g)(x) means f(g(x)): the rightmost function runs first and each result feeds leftwards. It reads backwards at first, but it matches how function application is written by hand, and it is the exact signature Redux uses for applyMiddleware.

Implement compose(...fns). It returns a function that invokes the rightmost function with all of the arguments it received, then passes each result to the next function to the left, and returns the leftmost function's result. Given no functions at all, the returned function returns its first argument unchanged.

Arguments

...fnsFunction[]
Any number of unary functions. The rightmost one may take any number of arguments.

Returns

Function — A function that applies fns right to left, threading the output of each into the next.

Examples

const addOne = (n) => n + 1;
const double = (n) => n * 2;

const run = compose(addOne, double);
run(5); // 11 — double(5) is 10, then addOne(10) is 11
const sum = (a, b) => a + b;
const run = compose((n) => n * 10, sum);

run(2, 3); // 50 — only the rightmost sees both arguments

Everything to the left is unary. The rightmost is the entry point.

What it has to do

  • Apply the functions right to left.
  • Pass every argument to the rightmost function; the rest each receive one value.
  • With no functions, return the first argument unchanged.
  • Work with a single function.

Notes

  • compose(f, g)(x) === f(g(x)) — the mathematical direction. If reading right-to-left bothers you, use pipe instead.
  • reduceRight fits beautifully, but you have to handle the rightmost call separately because it is the only one that spreads multiple arguments.
Asked atMetaShopify

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.