Part 2: Higher-Order Functions and Composition - Building Pipelines
Introduction
Functions as First-Class Citizens
// Function as a value
const add = (a: number, b: number): number => a + b;
const multiply = (a: number, b: number): number => a * b;
// Store functions in an object
const operations = {
add,
multiply,
subtract: (a: number, b: number): number => a - b
};
console.log(operations.add(5, 3)); // 8
console.log(operations.multiply(5, 3)); // 15
// Store functions in an array
const transforms: Array<(n: number) => number> = [
n => n * 2,
n => n + 10,
n => n ** 2
];
// Apply all transforms
let value = 5;
for (const transform of transforms) {
value = transform(value);
}
console.log(value); // ((5 * 2) + 10) ** 2 = 400Higher-Order Functions
Functions as Arguments
Functions as Return Values
Map, Filter, Reduce
Map - Transform Each Element
Filter - Select Elements
Reduce - Aggregate to Single Value
Real Example: API Response Processing
Function Composition
Manual Composition
Compose Utility
Pipe Utility
Real Example: Data Validation Pipeline
Real Example: Request/Response Pipeline
Point-Free Style
Real Example: Data Processing Pipeline
Chaining Operations
Best Practices
1. Keep Functions Small and Focused
2. Use Descriptive Names
3. Prefer Declarative Over Imperative
What's Next
PreviousPart 1: Pure Functions and Immutability - Predictable CodeNextPart 3: Closures and Currying - Function Factories
Last updated