Compose Functions in JavaScript

Level 4256 keystrokes

Function composition combines multiple functions into one, applying them right-to-left.

JavaScript code

// Compose function using reduceRight
// Takes any number of functions and returns a new function
1const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);
// Define simple transformation functions
2const add5 = x => x + 5;
3const multiply2 = x => x * 2;
4const subtract3 = x => x - 3;
// Compose them: first add5, then multiply2, then subtract3
5const calc = compose(subtract3, multiply2, add5);
// calc(10) = subtract3(multiply2(add5(10))) = (10+5)*2-3 = 27
6console.log(calc(10));
// calc(0) = subtract3(multiply2(add5(0))) = (0+5)*2-3 = 7
7console.log(calc(0));

Output

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

  • =× 11
  • (× 10
  • )× 10
  • ;× 7
  • .× 6
  • >× 6
  • ,× 4
  • -× 1
  • *× 1
  • +× 1

More JavaScript examples at level 4

← JavaScript typing practice