Compose functions right to left
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 11const sum = (a, b) => a + b;
const run = compose((n) => n * 10, sum);
run(2, 3); // 50 — only the rightmost sees both argumentsEverything 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, usepipeinstead.reduceRightfits beautifully, but you have to handle the rightmost call separately because it is the only one that spreads multiple arguments.
Stuck? The javascript course covers everything this challenge needs.
- 1.applies functions right to left
- 2.gives every argument to the rightmost function
- 3.records the order of execution
- 4.with no functions returns its first argument
- 5.works with a single function
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.