Chaining Lazy Operations
What you'll learn: How to compose multiple lazy transformations (map, filter, take, etc.) without creating intermediate arrays or forcing evaluation until the final step.
The Power of Composition
When you chain operations on arrays, each method call processes the entire array immediately, creating intermediate arrays along the way. With lazy iterators, you can chain transformations that only run when needed—one element at a time, as you consume the result.
Think of it like a factory assembly line: instead of completing all stations for all items before moving to the next station, each item flows through all stations only when requested.
How Chaining Works
Each lazy operation returns a new iterator that wraps the previous one. When you finally pull values (with for-of, spreading, or calling .next()), the chain executes backwards—the outermost iterator asks the next one for a value, which asks the next, all the way down to the source.
function* lazyMap(iterable, fn) {
for (const value of iterable) {
yield fn(value);
}
}
function* lazyFilter(iterable, predicate) {
for (const value of iterable) {
if (predicate(value)) yield value;
}
}
function* lazyTake(iterable, n) {
let count = 0;
for (const value of iterable) {
if (count++ >= n) break;
yield value;
}
}
function* range(start) {
while (true) yield start++;
}
// Chain operations - nothing runs yet!
const pipeline = lazyTake(
lazyFilter(
lazyMap(range(1), x => x * x),
x => x % 2 === 0
),
3
);
// Only now do we compute: just 3 even squares
console.log([...pipeline]); // [4, 16, 36]
This chain squares numbers, filters for evens, takes 3—but only generates as many source numbers as needed (about 6), never materializing intermediate arrays.
Key Takeaway: Chaining lazy operations lets you build complex data pipelines that process one value at a time, avoiding memory overhead and enabling efficient work with infinite sequences.