Careeroza
Composition & Pipelines
compose and pipe
Example
Build complex behaviour from small, single-purpose functions. pipe applies them left to right:
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const dashes = (s) => s.replace(/\s+/g, "-");
const slugify = pipe(trim, lower, dashes);
console.log(slugify(" Learn Functional JavaScript "));
const applyDiscount = (p) => p * 0.9;
const addTax = (p) => p * 1.18;
const round = (p) => Math.round(p);
console.log(pipe(applyDiscount, addTax, round)(1000));Output
learn-functional-javascript 1062
Declarative Data Processing
Example
Describe what you want instead of how to loop:
const orders = [
{ customer: "Asha", amount: 1200, status: "paid" },
{ customer: "Vikram", amount: 300, status: "refunded" },
{ customer: "Asha", amount: 800, status: "paid" },
{ customer: "Neha", amount: 450, status: "paid" },
];
const revenueByCustomer = orders
.filter((o) => o.status === "paid")
.reduce((acc, o) => ({ ...acc, [o.customer]: (acc[o.customer] ?? 0) + o.amount }), {});
console.log(revenueByCustomer);Output
{ Asha: 2000, Neha: 450 }