Chaining Lazy Operations
You'll learn how to compose multiple lazy generator operations into efficient pipelines that process items one-at-a-time without creating intermediate arrays.
The Power of the Pipeline
Think of a factory assembly line where each station does one task. Instead of finishing all items at station 1, then moving everything to station 2, imagine each item moving through all stations before the next item starts. That's lazy chaining—each value flows through the entire pipeline before the next one begins.
When you chain lazy operations (like your lazyMap and lazyFilter generators), they compose beautifully. Each generator yields to the next, processing one item at a time through the entire chain.
Building a Lazy Pipeline
function* lazyMap(iterable, fn) {
for (const item of iterable) {
yield fn(item);
}
}
function* lazyFilter(iterable, predicate) {
for (const item of iterable) {
if (predicate(item)) yield item;
}
}
function* range(start, end) {
for (let i = start; i <= end; i++) {
yield i;
}
}
// Chain operations together
const pipeline = lazyFilter(
lazyMap(range(1, 1000), x => x * 2),
x => x % 3 === 0
);
// Nothing computed yet!
const first = pipeline.next().value; // 6 (only processes items until first match)
Each next() call pulls one value through the entire chain. The range yields 1, lazyMap doubles it to 2, lazyFilter rejects it, then the cycle repeats with 2, then 3 (becomes 6, passes filter, returned).
Key Takeaway: Chaining lazy operations creates efficient pipelines where each item flows through all transformations before the next item is touched, avoiding intermediate arrays and enabling early termination.