Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Function composition combines simple functions to build more complex ones. Think of it as a pipeline where data flows through transformations!
(f ∘ g)(x) = f(g(x))g becomes input of fconst double = x => x * 2; const square = x => x * x; const addOne = x => x + 1; // Nested calls (hard to read) const result = addOne(square(double(3))); console.log(result); // 37 // Step by step (verbose) const step1 = double(3); // 6 const step2 = square(step1); // 36 const step3 = addOne(step2); // 37 // Hard to reuse this pattern
const double = x => x * 2; const square = x => x * x; const addOne = x => x + 1; // Compose helper const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x); // Create composed function const transform = compose(addOne, square, double); console.log(transform(3)); // 37 // Reusable and readable! const data = [1, 2, 3, 4, 5]; console.log(data.map(transform)); // [5, 17, 37, 65, 101]
Two ways to compose functions
// With points (parameters) const doubleAll = numbers => numbers.map(x => x * 2); const sumAll = numbers => numbers.reduce((a, b) => a + b, 0); // Point-free (no parameters mentioned) const double = x => x * 2; const sum = (a, b) => a + b; const doubleAllPointFree = arr => arr.map(double); const sumAllPointFree = arr => arr.reduce(sum, 0); // Or even more point-free const map = fn => arr => arr.map(fn); const reduce = (fn, init) => arr => arr.reduce(fn, init); const doubleAllClean = map(double); const sumAllClean = reduce(sum, 0); const numbers = [1, 2, 3, 4, 5]; console.log(doubleAllClean(numbers)); // [2, 4, 6, 8, 10] console.log(sumAllClean(numbers)); // 15 // Compose point-free functions const sumOfDoubles = pipe( map(double), reduce(sum, 0) ); console.log(sumOfDoubles(numbers)); // 30
Create a functional toolkit
Compose async functions
Transform raw data into presentation format
Build complex from simple
f(g(x)) - output of g feeds into f
Pipe: left to right (intuitive)
Compose: right to left (mathematical)
No explicit parameters
Focus on function composition
Create data transformation flows
Easy to test and maintain