Sub topic 3
Array Methods or Iterator Helpers?
This chapter assumes you know the iterator protocol, generators, and the map, filter, take, and drop helpers covered earlier.
Choosing Between Them
| Need | Use |
|---|---|
| Random access, `length`, sorting, reusing the data | Array methods |
| Infinite or very large sources | Iterator helpers |
| Stopping early without computing the rest | Iterator helpers |
| Small data that is read several times | Array methods |
Array methods are eager. Each step builds a full new array. Iterator helpers are lazy. They pass one value at a time through the whole chain and never build intermediate arrays.
Pitfalls: Single Use and Arrays
An iterator pipeline can be consumed only once:
const evens = [1, 2, 3, 4].values().filter((n) => n % 2 === 0);
console.log([...evens]); // [2, 4]
console.log([...evens]); // []Arrays are iterables, not iterators. [1, 2].take(1) throws a TypeError. Call .values() first to get an iterator.
The Counter Argument
Helper callbacks receive (value, counter). The counter starts at 0 and goes up by one for each value the helper sees:
const labels = ['a', 'b', 'c']
.values()
.map((value, index) => `${index}:${value}`)
.toArray();
console.log(labels); // ['0:a', '1:b', '2:c']Unlike array callbacks, helper callbacks get no third argument for the collection.
Iterator.from
Iterator.from wraps any iterable, or any object with a next method, so the helpers become available on it:
const iteratorLike = {
i: 0,
next() {
return this.i < 3
? { value: this.i++, done: false }
: { value: undefined, done: true };
},
};
console.log(Iterator.from(iteratorLike).map((x) => x + 1).toArray()); // [1, 2, 3]Eager Argument Errors
The pipeline runs lazily, but arguments are checked as soon as you call the helper. take(-1) and drop(NaN) throw a RangeError right away. A callback that is not a function throws a TypeError right away.
Early Termination and Cleanup
When take reaches its limit, it calls return() on the source iterator. That runs the generator's finally block:
function* source() {
try {
yield 1;
yield 2;
} finally {
console.log('cleanup');
}
}
console.log(source().take(1).toArray());
// cleanup
// [1]some, every, and find also close the source when they stop early.
flatMap
flatMap maps each value to an iterator or iterable and yields that result's items one by one. A string returned from the callback throws a TypeError, so wrap strings in an array.
const out = [1, 2].values().flatMap((n) => [n, n * 10]).toArray();
console.log(out); // [1, 10, 2, 20]Feature Detection
const supported =
typeof Iterator !== 'undefined' &&
typeof Iterator.prototype.map === 'function';
console.log(supported);Exercise
A generator has a finally block that logs "closed". What does gen().drop(1).take(2).toArray() log if the generator yields 5 values?
Show answer
It logs "closed" once, and toArray returns the second and third values. When take reaches its limit of 2, it calls return() through drop on the generator, and that runs the finally block.