Real-World Composition Patterns
You'll learn: How to apply function composition to solve common real-world problems like validation, data transformation, and processing workflows.
Composition truly shines when you build pipelines that solve actual business problems. Instead of nesting function calls or writing procedural code with temporary variables, you can chain operations that read like a description of what you're doing.
Validation Pipeline
Imagine validating user input. Rather than one giant function with if-statements, compose smaller validators:
const isNotEmpty = str => str.length > 0 || 'Cannot be empty';
const isEmail = str => /@/.test(str) || 'Invalid email';
const trimmed = str => str.trim();
// Pipe for left-to-right readability
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const validateEmail = pipe(
trimmed,
isNotEmpty,
isEmail
);
validateEmail(' user@example.com '); // passes all checks
Data Transformation Workflow
Processing API responses becomes elegant with composition:
const parseJSON = data => JSON.parse(data);
const extractUsers = obj => obj.users;
const activeOnly = users => users.filter(u => u.active);
const mapToNames = users => users.map(u => u.name);
const getActiveUserNames = pipe(
parseJSON,
extractUsers,
activeOnly,
mapToNames
);
const response = '{"users":[{"name":"Alice","active":true},{"name":"Bob","active":false}]}';
getActiveUserNames(response); // ['Alice']
Why This Works
Each function does one thing clearly. You can test each piece independently, reuse them across different pipelines, and read the composition as a step-by-step recipe. It's like an assembly line: raw material enters, each station performs its task, and finished product exits.
Key Takeaway: Real-world composition turns complex workflows into readable, testable pipelines by combining small, focused functions that each handle one transformation or validation step.