Imperative to declarative: loops into pipelines
Say what you want from a list, and let the pipeline do the walking.
Watch the narrated video
Every step
Problem
Steps 1–4Refactor
Steps 5–8Payoff
Steps 9–10Recap
Steps 11–12The code: before and after
Before
type Order = {
customer: string;
status: string;
total: number;
};
function shippedRevenue(orders: Order[]): number {
let sum = 0;
for (const o of orders) {
if (o.status === "SHIPPED") sum += o.total;
}
return sum;
}
function topCustomers(orders: Order[]): string[] {
const shipped: Order[] = [];
for (const o of orders) {
if (o.status === "SHIPPED") shipped.push(o);
}
shipped.sort((a, b) => b.total - a.total);
const names: string[] = [];
for (const o of shipped) {
if (names.length === 3) break;
if (!names.includes(o.customer)) names.push(o.customer);
}
return names;
}
function dailyDigest(): string {
const orders: Order[] = [
{ customer: "ana@shop.com", status: "SHIPPED", total: 120 },
{ customer: "qa@test.shop", status: "SHIPPED", total: 999 },
{ customer: "bo@shop.com", status: "PENDING", total: 80 },
{ customer: "cy@shop.com", status: "SHIPPED", total: 45 },
{ customer: "ana@shop.com", status: "SHIPPED", total: 60 },
];
const revenue = shippedRevenue(orders);
const top = topCustomers(orders).join(", ");
return `${revenue} | ${top}`;
}After
type Order = {
customer: string;
status: string;
total: number;
};
function countsAsSale(o: Order): boolean {
return o.status === "SHIPPED" &&
!o.customer.endsWith("@test.shop");
}
function shippedRevenue(orders: Order[]): number {
return orders
.filter(countsAsSale)
.map((o) => o.total)
.reduce((sum, total) => sum + total, 0);
}
function topCustomers(orders: Order[]): string[] {
const customers = orders
.filter(countsAsSale)
.sort((a, b) => b.total - a.total)
.map((o) => o.customer);
return [...new Set(customers)].slice(0, 3);
}
function dailyDigest(): string {
const orders: Order[] = [
{ customer: "ana@shop.com", status: "SHIPPED", total: 120 },
{ customer: "qa@test.shop", status: "SHIPPED", total: 999 },
{ customer: "bo@shop.com", status: "PENDING", total: 80 },
{ customer: "cy@shop.com", status: "SHIPPED", total: 45 },
{ customer: "ana@shop.com", status: "SHIPPED", total: 60 },
];
const revenue = shippedRevenue(orders);
const top = topCustomers(orders).join(", ");
return `${revenue} | ${top}`;
}Transcript, step by step
Problem
Step 1: A sales report in loops Before
This sales report works on an array of orders, and each order has a customer email, a status and a total. Shipped revenue walks the array and adds the total of every shipped order to a running sum. Top customers copies the shipped orders into an array, sorts them by total, and walks them again to collect three different customers. The daily digest builds today's orders and returns both numbers in one line. One of those orders comes from a test account at test dot shop, and it's the biggest order of the day.
Step 2: Leave out test orders Code smell
Finance says test orders, from customers at test dot shop, must not count in either number. So the check goes into the if in shipped revenue, and into the if in the first loop of top customers. This code is imperative, because it spells out how to walk the array step by step, so you have to replay the loop in your head to learn what it's for. You can see it in the running sum here, the temporary shipped array here, and the break and the includes check here.
Step 3: The rule, twice Code smell
The rule for what counts as a sale is now written twice, so the next rule has to be found and added twice too. And in top customers, the filter, the ranking, the repeat check and the stop at three are tangled across two loops. So you replay both loops line by line to see which one decides what counts as a sale, and where a new condition belongs.
Step 4: Back it out, then pipelines Plan
Let's back that change out. Declarative code says what you want, so we'll turn each loop into a collection pipeline, a chain of operations where each one has one job, and add the rule after that.
Refactor
Step 5: Shipped revenue as a chain Replace Loop with Pipeline
Shipped revenue now returns one chain of array methods on the orders. Filter keeps the shipped ones, map takes each total, and reduce adds them up, starting from zero. The running sum is gone, because reduce carries that total for you, and the digest still shows twelve twenty-four.
Step 6: Filter and sort in one chain Replace Loop with Pipeline
In top customers, the first loop and the sort become one pipeline. Filter keeps the shipped orders, and sort ranks them by total from high to low. Sort changes the array it's called on, but here that's the new array filter returned, so the caller's orders stay in their order. Nobody fills a temporary array by hand anymore, and the second loop still reads from shipped, so the output stays the same.
Step 7: The second loop joins Replace Loop with Pipeline
Now the second loop joins the same pipeline. Map takes each order's customer, a Set drops the repeats, and slice keeps the first three names. Arrays have no distinct method, so the Set does that job, and spreading it back into an array gives the names in the order they were added. The output doesn't change, because the Set keeps a name the first time it sees it, as the includes check did, and slice keeps three names, as the break did.
Step 8: Name the sale rule Extract Function
The status test now sits in two filters, so we extract it into one function called counts as sale. Both pipelines hand that function to filter by name, first in shipped revenue and then in top customers. Now the diagram shows both functions asking one place what a sale is.
Payoff
Step 9: Test orders, one edit Payoff
Now Finance's rule goes in again, and this time it's one edit inside counts as sale. Neither pipeline changed, because both of them ask counts as sale and don't care what it checks. So the digest now shows two twenty-five, with Ana and Cy as the top customers.
Step 10: Why it was easy Payoff
The running sum moved into reduce here, the temporary array became a sorted chain here, and the break and the includes check became a Set and a slice here. Top customers now shows each job on its own line, so you can see at a glance that a new sale rule belongs in the filter. Giving that rule one home for both pipelines came from Extract Function, and the pipelines made the spot easy to find.
Recap
Step 11: Where we started, where we ended Before / after
On the left, shipped revenue keeps a running sum, and top customers fills a temporary array, checks includes, and breaks at three. On the right, each function is one pipeline, and each line in it does one job. And counts as sale holds the rule for both of them, so Finance's next rule is one edit too.
Step 12: When to reach for it Takeaways
Reach for a pipeline when a loop filters, transforms or totals a collection, and you want each job readable on its own line. Skip it when each step depends on the one before, like a running balance that stops at the first overdraft, because the loop says that more plainly than a reduce. You'll spot it by a temporary array filled in a loop, a running total, or a break or flag that stops early. The array methods some and every work this way already, because they stop at the first answer, like a loop with a flag and a break.