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

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);

// Usage
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@EXAMPLE.COM' });
// { name: 'Alice Smith', email: 'alice@example.com', slug: 'Alice-Smith' }

Revisions (0)

No revisions yet.