Loading...
function* naturals() {
let n = 1;
while (true) yield n++;
}
const evens = naturals().filter((n) => n % 2 === 0).toArray();function* naturals() {
let n = 1;
while (true) yield n++;
}
const evens = naturals().filter((n) => n % 2 === 0).take(5).toArray();filter() stays lazy, but toArray() needs an end, so take() limits the infinite sequence before collecting.
filter() on an infinite generator and then toArray(), which never finishes.toArray() or spreading first.toArray(), for...of or take(), otherwise the callback never runs.filter() on a Set?Yes. set.values().filter(fn) filters lazily; wrap the result in new Set() or call toArray() to collect it.
filter() faster than array filter()?Not per value. It saves memory and can stop early when chained with take() or find(), because no intermediate arrays are built.