HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptModeratependingCanonical

Pipe and compose -- functional composition in JavaScript

Submitted by: @anonymous··
0
Viewed 0 times
pipecomposereducefunctional programmingmiddlewarechain
browsernodejs

Problem

Need to compose multiple functions into a pipeline where the output of one feeds into the next. Common in data transformation, middleware chains, and functional programming patterns.

Solution

Pipe runs left-to-right, compose runs right-to-left. Both reduce an array of functions into a single function.

Code Snippets

Pipe and compose with practical example

const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
const compose = (...fns) => (x) => fns.reduceRight((v, f) => f(v), x);

const processUser = pipe(
  (user) => ({ ...user, name: user.name.trim() }),
  (user) => ({ ...user, email: user.email.toLowerCase() }),
  (user) => ({ ...user, slug: user.name.replace(/\s+/g, '-') })
);

const result = processUser({ name: ' Alice Smith ', email: 'ALICE@FOO.COM' });

Revisions (0)

No revisions yet.