Skip to content Skip to sidebar Skip to footer

Can I Make An Iterator With A Simple Function? (no Generator Or Symbol.iterator)

I have been trying to make an iterator using a plain function, without a generator or using the Symbol.iterator protocol for academic purposes. For that, I have made a function tha

Solution 1:

The problem is that your iterateThis function returns an iterator but the for/of construct expects a iterable.

Okay, wait, whats the difference?

From MDN's page on iteration protocols:

In order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant Symbol.iterator:

On the other hand:

An object is an iterator when it implements a next() method with the following semantics: Ommited due to length, TL;DR: The next method returns an object of the form: {value: T, done: boolean}

They are related in that calling the @@iterator method of an iterable returns an iterator.

The for/of loop always expects an iterable, so if you want to use for/of, you have to use @@iterator/Symbol.iterator. There's just no way around it as far as I know. But your snippet can be easily modified to use it by just creating an object that returns your iterator when it's Symbol.iterator method is called:

functioniterateThis(arr){
    let i = 0;
    return {
        next: function() {
            return i < arr.length ?
                {value: arr[i++], done: false} :
                {done: true};
        }
     };
}

functionmakeIterableFromIterator(iterator) {
  return {
    [Symbol.iterator]: function() {
      return iterator;
    }
  }
}

const iterator = iterateThis([1, 2, 3, 4, 5]);
const iterable = makeIterableFromIterator(iterator);

for (item of iterable) {
  console.log(item);
}

Post a Comment for "Can I Make An Iterator With A Simple Function? (no Generator Or Symbol.iterator)"