Pipeline Composition in JavaScript

Level 5604 keystrokes

This implements pipe and compose for function composition patterns.

JavaScript code

// pipe: left-to-right function composition
// Value flows through functions in order: f1 -> f2 -> f3
1const pipe = (...fns) => (value) =>
2 fns.reduce((acc, fn) => fn(acc), value);
3
// compose: right-to-left function composition (traditional)
// Value flows through functions in reverse: f3 <- f2 <- f1
4const compose = (...fns) => (value) =>
5 fns.reduceRight((acc, fn) => fn(acc), value);
6
// Simple transformation functions
7const double = x => x * 2;
8const addTen = x => x + 10;
9const square = x => x * x;
10
// pipe: 5 -> double -> addTen -> square
// 5 -> 10 -> 20 -> 400
11const piped = pipe(double, addTen, square);
// compose(square, addTen, double) applies double first, then addTen, then square
// Same result: 5 -> 10 -> 20 -> 400
12const composed = compose(square, addTen, double);
13
14console.log("Piped:", piped(5));
15console.log("Composed:", composed(5));
16
// Practical example: name processing pipeline
17const processName = pipe(
// Remove leading and trailing spaces
18 str => str.trim(),
// Make everything lowercase: "john doe"
19 str => str.toLowerCase(),
// Capitalize the first letter of each word: "John Doe"
20 str => str.split(" ").map(w => w[0].toUpperCase() + w.slice(1)).join(" ")
21);
22console.log(processName(" john DOE "));

Output

Piped: 400
Composed: 400
John Doe
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 26
  • )× 26
  • =× 21
  • .× 18
  • >× 13
  • ,× 12
  • ;× 11
  • "× 10
  • :× 2
  • *× 2

More JavaScript examples at level 5

← JavaScript typing practice