29Implement compose() and pipe()
mediumAbout 35 minutesCodingfunctional-programminghigher-order-functions
Problem
Implement two helpers that chain functions:
pipe(f, g, h)returns a function that runsf, theng, thenh:h(g(f(...args))). Left to right, like reading a recipe.compose(f, g, h)runs right to left:f(g(h(...args))). This is the mathematical order, used by Redux'scompose.
const slugify = pipe(
(s) => s.trim(),
(s) => s.toLowerCase(),
(s) => s.replace(/\s+/g, "-"),
);
slugify(" Hello World "); // "hello-world"
const add = (a, b) => a + b;
const double = (n) => n * 2;
compose(double, add)(2, 3); // 10Requirements
- The first function to run may take several arguments; every later one receives the previous result.
- With no functions, return the identity function (
x => x). - Throw a
TypeErrorwhen creating the chain if any argument is not a function, not later when it runs.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Step-by-step
Check every argument with typeof fn === "function" when pipe is called. An error at setup time points to the real mistake; an error deep inside a later call does not.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 4 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.