Taking and Dropping with Iterators
You'll learn: How to implement take(n) and drop(n) helpers that extract finite slices from potentially infinite or very large iterators.
The Core Idea
When working with lazy iterators (especially infinite ones like the Fibonacci sequence), you often need to:
- Take the first
nvalues and stop - Drop (skip) the first
nvalues and continue with the rest
These operations let you slice infinite streams without evaluating everything upfront—perfect for lazy evaluation.
Implementing take(n)
Think of take(n) like filling a bucket: once you've collected n items, you stop drawing from the source.
function* take(iterable, n) {
let count = 0;
for (const value of iterable) {
if (count >= n) return;
yield value;
count++;
}
}
// Use with an infinite iterator
function* infiniteNumbers() {
let i = 0;
while (true) yield i++;
}
for (const num of take(infiniteNumbers(), 5)) {
console.log(num); // 0, 1, 2, 3, 4
}
Implementing drop(n)
drop(n) skips the first n values, then yields everything after:
function* drop(iterable, n) {
let count = 0;
for (const value of iterable) {
if (count < n) {
count++;
continue;
}
yield value;
}
}
for (const num of take(drop(infiniteNumbers(), 10), 3)) {
console.log(num); // 10, 11, 12
}
Notice how we composed take and drop—this is the power of lazy iterators!
Why This Matters
These helpers transform infinite or huge data sources into manageable, finite chunks without loading everything into memory. You're creating pipelines that only compute what you actually consume.
Key Takeaway: take(n) and drop(n) are essential tools for slicing lazy iterators, enabling efficient processing of infinite sequences by extracting only the values you need, when you need them.