Taking and Dropping from Lazy Sequences
You'll learn how to create utilities that grab the first N items or skip the first N items from lazy sequences, giving you fine control over potentially infinite generators.
The Core Idea
When working with lazy sequences (generators), you often want to take only the first few items or skip over some before consuming the rest. Think of it like a buffet line: "take" means grabbing the first 5 dishes you see, while "drop" means skipping the first 3 and starting from the fourth.
Without these utilities, you'd consume items manually in loops. With them, you build reusable, composable tools that work with any lazy sequence—even infinite ones.
Implementing Take
A take generator yields up to N items from any iterable, then stops:
function* take(iterable, n) {
let count = 0;
for (const value of iterable) {
if (count >= n) return;
yield value;
count++;
}
}
function* range(start) {
let i = start;
while (true) yield i++;
}
// Take first 5 from infinite range
for (const num of take(range(10), 5)) {
console.log(num); // 10, 11, 12, 13, 14
}
Implementing Drop
A drop generator skips the first N items, then yields everything after:
function* drop(iterable, n) {
let count = 0;
for (const value of iterable) {
if (count < n) {
count++;
continue;
}
yield value;
}
}
Chaining Take and Drop
These utilities compose beautifully:
// Skip first 3, then take next 4
const result = take(drop(range(0), 3), 4);
for (const num of result) {
console.log(num); // 3, 4, 5, 6
}
Key Takeaway: take and drop utilities let you slice lazy sequences on-the-fly, controlling consumption without evaluating the entire (potentially infinite) source upfront.