Helping Iterators
Michael Ficarra • June 2024�(iterator helpers champion)
easiest quiz of your life:
what do all of these JavaScript features have in common?
for (let a of iterable); | [ ...iterable ] |
let [a, b] = iterable; | Object.fromEntries(iterable) |
for-of loop
Array spread
positional destructuring
iterable-taking built-ins
ITERATOR PROTOCOL!
what makes iterators so great?
they're lazy sequences!
iteration protocol (approximation)
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface Iterator<T> {
next(): IteratorResult<T>;
return?(): IteratorResult<T>;
}
type IteratorResult<T>
= { done: false, value: T }
| { done: true, value?: undefined };
easy ways to create your own iterators
1) iterate a finite collection type:
Object.fromEntries(map.entries())
2) write a generator:
function* nats() {
for (let i = 0; ; ++i) {
yield i;
}
}
let [zero, one, two] = nats();
Iterator.prototype
Stage 3: iterator helpers MVP
(basically just Array analogues)
transform iterators
consume iterators
Iterator.from: ensure an iterator inherits from Iterator.prototype
iterator follow-on proposals
active iterator follow-on proposals
Stage 2 proposal: joint iteration (going for Stage 2.7 this week!)
Iterator.zipToArrays(iterableOfIterables [ , options ])
Iterator.zipToObjects(namedIterables [ , options ])
Stage 1 proposal: iterator sequencing (going for Stage 2 this week!)
Iterator.concat(...iterators)
Stage 1 proposal: iterator chunking
iterator.chunks(chunkSize)
iterator.windows(windowSize, stepSize)
Stage 1 proposal: iterator unique
iterator.distinct( [ exemplarMapper ] )
CAUTION: names and shapes of APIs in in-progress proposals are subject to change
planned iterator follow-on proposals
the future of iterators is looking bright!
postlude: async iterator helpers are WIP
urls
.toAsync()
.map(u => fetch(u))
.buffered(2)
.toArray()