Iterator helpers
- Version
- es2025
- Since
- es2025
- Review
- Draft
Summary#
Iterator helpers add methods such as map, filter, take and drop to iterators. Those four are lazy: they pull source values only as the result is consumed.
Syntax#
const results = iterator.filter(predicate).map(transform).take(limit).toArray();
const wrapped = Iterator.from(iterableOrIterator);
Example#
function* naturals() {
let value = 1;
while (true) yield value++;
}
const evens = naturals()
.filter((value) => value % 2 === 0)
.map((value) => value * 10)
.take(3);
console.log(evens.toArray().join(","));
console.log(evens.toArray().length);
console.log(Iterator.from(["a", "b", "c"]).drop(1).toArray().join(","));
Expected output#
20,40,60
0
b,c
Common mistakes#
Calling toArray on an infinite iterator never finishes, so limit it with take first. An iterator is consumed once: create a new one to traverse again. An array is iterable but is not an iterator, so call array.values() or Iterator.from(array) before using a helper such as take.
Version applicability#
ES2025 added iterator helpers. Older runtimes need a polyfill or a generator that implements the same steps.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0