Function Composition in JavaScript

Level 5317 keystrokes

Function composition combines multiple functions into a single function that processes data sequentially.

JavaScript code

// Compose applies functions right to left
1const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
// Pipe applies functions left to right
2const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x);
// Simple function that adds 1
3const addOne = x => x + 1;
// Simple function that doubles
4const double = x => x * 2;
// Simple function that squares
5const square = x => x * x;
// compose: addOne(3)=4, double(4)=8, square(8)=64
6console.log(compose(square, double, addOne)(3));
// pipe: addOne(3)=4, double(4)=8, square(8)=64
7console.log(pipe(addOne, double, square)(3));

Output

64
64
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.

  • (× 14
  • )× 14
  • =× 14
  • .× 10
  • >× 9
  • ,× 8
  • ;× 7
  • *× 2
  • +× 1

More JavaScript examples at level 5

← JavaScript typing practice