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 left1const compose = (...fns) => (x) => // reduceRight processes from right to left // Each function receives the result of the previous one2 fns.reduceRight((acc, fn) => fn(acc), x);3 // Simple transformation functions// Multiplies by 24const double = (n) => n * 2;// Adds 105const addTen = (n) => n + 10;// Squares the number6const 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)=40010console.log(transform(5));// 3 -> addTen(3)=13 -> double(13)=2611console.log(compose(double, addTen)(3));Output
400 26
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