Function Composition in JavaScript

Level 5286 keystrokes

Implements function composition to combine multiple functions into a single transformation.

JavaScript code

// compose takes any number of functions as arguments
// Returns a function that applies them from right to left
1const compose = (...fns) => (x) =>
// reduceRight processes from right to left
// Each function receives the result of the previous one
2 fns.reduceRight((acc, fn) => fn(acc), x);
3
// Simple transformation functions
// Multiplies by 2
4const double = (n) => n * 2;
// Adds 10
5const addTen = (n) => n + 10;
// Squares the number
6const square = (n) => n * n;
7
// Create a composed function: square(addTen(double(x)))
8const transform = compose(square, addTen, double);
9
// 5 -> double(5)=10 -> addTen(10)=20 -> square(20)=400
10console.log(transform(5));
// 3 -> addTen(3)=13 -> double(13)=26
11console.log(compose(double, addTen)(3));

Output

400
26
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
  • =× 11
  • ;× 7
  • .× 6
  • >× 6
  • ,× 5
  • *× 2
  • +× 1

More JavaScript examples at level 5

← JavaScript typing practice