Problem Statement
What is function composition?
Explanation
Function composition is combining two or more functions to create a new function where the output of one function becomes the input of the next.
It follows the mathematical concept of composition: f composed with g of x equals f of g of x.
Composition makes code more readable and reusable by breaking complex operations into simple functions.
The compose function typically executes from right to left. Pipe function executes from left to right.
Composition is a core principle of functional programming.
It enables building complex behavior from simple, testable functions.
Code Solution
SolutionRead Only
// Simple functions
const add5 = x => x + 5;
const multiply2 = x => x * 2;
const subtract3 = x => x - 3;
// Manual composition
const result = subtract3(multiply2(add5(10)));
console.log(result); // (10 + 5) * 2 - 3 = 27
// Compose function (right to left)
function compose(...fns) {
return function(value) {
return fns.reduceRight((acc, fn) => fn(acc), value);
};
}
const calculate = compose(subtract3, multiply2, add5);
console.log(calculate(10)); // 27
// Pipe function (left to right)
function pipe(...fns) {
return function(value) {
return fns.reduce((acc, fn) => fn(acc), value);
};
}
const calculate2 = pipe(add5, multiply2, subtract3);
console.log(calculate2(10)); // 27 (same result)
// Practical example - data transformation
const users = [
{ name: 'john', age: 25, active: true },
{ name: 'jane', age: 30, active: false },
{ name: 'bob', age: 35, active: true }
];
// Individual functions
const filterActive = users => users.filter(u => u.active);
const mapNames = users => users.map(u => u.name);
const capitalizeNames = names => names.map(n => n.toUpperCase());
// Compose them
const getActiveUserNames = pipe(
filterActive,
mapNames,
capitalizeNames
);
console.log(getActiveUserNames(users)); // ['JOHN', 'BOB']
// String manipulation example
const trim = str => str.trim();
const toLowerCase = str => str.toLowerCase();
const removeSpaces = str => str.replace(/\s+/g, '-');
const slugify = pipe(trim, toLowerCase, removeSpaces);
console.log(slugify(' Hello World ')); // 'hello-world'
// With arrow functions
const double = x => x * 2;
const addTen = x => x + 10;
const square = x => x * x;
const complexCalc = pipe(double, addTen, square);
console.log(complexCalc(5)); // ((5 * 2) + 10) ^ 2 = 400
// Reusable composed functions
const validateEmail = pipe(
email => email.trim(),
email => email.toLowerCase(),
email => email.includes('@')
);
console.log(validateEmail(' Test@Email.com ')); // true