Pipe Function in JavaScript

Level 5388 keystrokes

Pipe creates a function pipeline that processes data through multiple transformations left-to-right.

JavaScript code

// Pipe function using reduce (left-to-right)
// Unlike compose which is right-to-left
1const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
2
// Define individual transformation functions
3const trim = s => s.trim();
4const toLowerCase = s => s.toLowerCase();
// split turns the string into an array of words
5const split = s => s.split(" ");
// join glues the words back together with "-"
6const join = arr => arr.join("-");
7
// Create a slugify function by piping transformations
// Data flows: trim -> toLowerCase -> split -> join
8const slugify = pipe(trim, toLowerCase, split, join);
9
// " Hello World " -> "hello-world"
10console.log(slugify(" Hello World "));
// "JavaScript Is Fun" -> "javascript-is-fun"
11console.log(slugify("JavaScript Is Fun"));
// " ONE TWO THREE " -> "one-two-three"
12console.log(slugify(" ONE TWO THREE "));

Output

hello-world
javascript-is-fun
one-two-three
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.

  • (× 16
  • )× 16
  • =× 13
  • .× 11
  • "× 10
  • ;× 9
  • >× 7
  • ,× 5
  • -× 1

More JavaScript examples at level 5

← JavaScript typing practice