Lazy Map with Generators
You'll learn how to transform values on-demand using generators, processing only what you need when you need it.
The Core Idea
Remember how arrays have a .map() method that transforms every element? That's eager—it processes the entire array immediately, creating a new array with all transformed values. With generators, you can build a lazy map that transforms values one-by-one, only as they're consumed. If you stop early, untouched values never get processed.
Think of it like a factory assembly line. An eager map runs the entire line at once, transforming every item before you see any results. A lazy map only transforms the item when you ask for it—saving time and memory when you don't need everything.
Implementing Lazy Map
Here's how to create a lazy map using generators:
function* lazyMap(iterable, transformFn) {
for (const value of iterable) {
yield transformFn(value);
}
}
// Example: square numbers lazily
function* range(start, end) {
for (let i = start; i <= end; i++) {
yield i;
}
}
const squared = lazyMap(range(1, 1000000), x => x * x);
// Nothing computed yet!
console.log(squared.next().value); // 1 (only now does 1*1 happen)
console.log(squared.next().value); // 4 (only now does 2*2 happen)
// The other 999,998 values are never computed
Notice how transformFn only runs when next() is called. You can iterate through millions of potential values without computing them all upfront.
// Works seamlessly with for...of
for (const num of lazyMap(range(1, 10), x => x * 2)) {
if (num > 12) break; // Stops early; remaining values never processed
console.log(num);
}
Key Takeaway: Lazy map with generators transforms values on-demand rather than all at once, enabling efficient memory usage and early termination without wasting computation on unused values.