Lazy Filter with Generators
You'll learn how to build a filter that tests and yields matching values one at a time, making data pipelines both memory-efficient and composable.
The Core Idea
Just like you built a lazy map, you can create a lazy filter using generators. Instead of creating a new array of filtered results all at once, a lazy filter tests each value only when requested and yields only those that pass the test. This is powerful when working with large or infinite sequences—you never materialize more results than you actually need.
Think of it like a bouncer at a club: they only let people through as they arrive, one at a time, checking credentials on the spot. No one maintains a pre-approved list of everyone who will eventually show up.
Building a Lazy Filter
function* lazyFilter(iterable, predicate) {
for (const value of iterable) {
if (predicate(value)) {
yield value;
}
}
}
function* infiniteNumbers() {
let n = 1;
while (true) yield n++;
}
const evens = lazyFilter(infiniteNumbers(), n => n % 2 === 0);
console.log(evens.next().value); // 2
console.log(evens.next().value); // 4
console.log(evens.next().value); // 6
The filter only runs when you call next(). Each value is tested on demand, not upfront.
Pipeline Composition
Combine lazyMap and lazyFilter for powerful, efficient pipelines:
function* lazyMap(iterable, fn) {
for (const value of iterable) {
yield fn(value);
}
}
const evensDoubled = lazyMap(
lazyFilter(infiniteNumbers(), n => n % 2 === 0),
n => n * 2
);
console.log(evensDoubled.next().value); // 4
console.log(evensDoubled.next().value); // 8
No intermediate arrays. No wasted computation.
Key Takeaway: Lazy filter with generators tests and yields matching values one at a time, enabling memory-efficient, composable data pipelines that only compute what you consume.