Pipe functions left to right
pipe(f, g)(x) means g(f(x)). Same machinery as compose, opposite direction, and far easier to read for a data transformation: trim, then split, then count.
Implement pipe(...fns). It returns a function that invokes the leftmost function with all of the arguments it received, then passes each result to the next function to the right, and returns the rightmost function's result. Given no functions at all, the returned function returns its first argument unchanged.
Arguments
...fnsFunction[]- Any number of unary functions. The leftmost one may take any number of arguments.
Returns
Function — A function that applies fns left to right, threading the output of each into the next.
Examples
const trim = (s) => s.trim();
const split = (s) => s.split(" ");
const count = (parts) => parts.length;
const wordCount = pipe(trim, split, count);
wordCount(" hello world "); // 2The reading order matches the data flow — trim, then split, then count.
pipe((a, b) => a + b, (n) => n * 10)(2, 3); // 50What it has to do
- Apply the functions left to right.
- Pass every argument to the leftmost function; the rest each receive one value.
- With no functions, return the first argument unchanged.
- Support a chain of more than two functions whose types change along the way.
Notes
pipe(f, g)(x) === g(f(x)). Same machinery ascompose, opposite direction — pick whichever reads better at the call site.- This is the shape of RxJS's
pipeand of the stage-2 pipeline operator proposal (x |> f |> g). Learn it once, apply it everywhere.
Stuck? The javascript course covers everything this challenge needs.
- 1.applies functions left to right
- 2.gives every argument to the leftmost function
- 3.records the order of execution
- 4.with no functions returns its first argument
- 5.chains transformations that change type
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.