melatonin
melatonin

Reputation: 81

IterableIterator in ES2015 - What is it?

When I implement the interface array, there are methods there return an IterableIterator. The IterableIterator extends from Iterator that I can understand well and makes sense to me.

interface IterableIterator<T> extends Iterator<T> {
    [Symbol.iterator](): IterableIterator<T>;
}

But what should I implement for Symbol.iterator. This also return an IterableIterator (recursion?) I don't understand the concept of IterableIterator. It would be great if someone could respond. Or could give me a source where this is described.

Upvotes: 8

Views: 20385

Answers (1)

Thai
Thai

Reputation: 11354

It is often useful for Iterator objects to become Iterable themselves, so that they can:

  • be used in a for..of loop
  • be spread into an array
  • be spread into a parameter list
  • be used in APIs that accept iterables like
    • Array.from
    • new Set
    • new Map

If an Iterator object is not Iterable, then they can’t be used in ways described above. The only way to iterate through it is to repeatedly call the .next() method. This is inconvenient. Therefore, most Iterator objects produced by ECMAScript APIs are also Iterable.

To make an Iterator Iterable, the [Symbol.iterator] method should return this.

For more information see:

Upvotes: 12

Related Questions