Z
Z
zlodiak2019-10-20 01:51:31
JavaScript
zlodiak, 2019-10-20 01:51:31

Are these iterators equivalent?

There are 2 iterable objects: a string and a custom one. In the custom one, the iter() method is called first, and then the next() method is called several times. as a result, all elements of the custom iterable object are displayed:

class Obj {
  constructor(word) {
    this.word = word;
  }

  iter() { return new Iterator(this.word); }
}


class Iterator {
  constructor(word) {
    this.word = word;
    this.index = 0;
  }

  next() {
    try {
      let letter = this.word[this.index];
      this.index += 1;
      return letter;
    } catch (err) {
      throw "StopIteration";
    }
  }

  iter() { return this; }
}

const obj = new Obj('sergey');
it = obj.iter();

console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());

Tell me if I'm right that in the case of a non-custom iterable object (string) the same sequence of operations occurs, but implicitly. That is, the string, getting into the loop context using the iter() method (the name may differ, that's not the point) returns an iterator. And then the loop implicitly kicks the next() method on each pass. As a result, all elements of the iterable object are displayed:for of
const s = 'sergey';

for (let char of s) {
  console.log(char);
}

At the same time, the string has an iter() method (the name may differ) from the parent object.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question