This is the ninth day of my participation in the First Challenge 2022. For details: First Challenge 2022.

Iterator Iterator Iterator

  • Iterator Iterator is an interface mechanism that provides uniform access to a variety of different data structures
  • Mainly for… of.. use
  • To arrange the members of a data structure in some order
  • In one sentence: Make non-iterable data structures iterable

Are you curious about it? Let’s take a look at what it takes to make non-iterable data structures iterable. The answer is bound to come at the end of the article.

A data structure with an Iterator interface

  • Array
  • Set
  • Map
  • String
  • TypeArray: A data structure similar to an array structure that describes the underlying binary
  • The Argiuments object of the function
  • The NodeList object

How can we tell if a data structure has an Iterator interface? We can print a map and find a Symbol. Iterator below the map’s prototype, which indicates that the map is a traversable data structure with an Iterator interface. Other things we can print and verify as well;

let map = new Map()
console.log(map);
Copy the code

Call the symbol. iterator method below the corresponding data structure

let map = new Map()
let foo = map[Symbol.iterator]()
console.log(foo.next()) //{value: undefined, done: true}
Copy the code

The following method allows us to determine whether an object is iterable

const isIterable = obj => obj ! = null && typeof obj[Symbol.iterator] === 'function';Copy the code

3. Simulate an traverser

The following code simulates implementing an iterator with the next() method, which we can see is exactly the same as next() for generator functions.

Iterable protocol and iterator protocol

Iterable protocol and iterator protocol

Iterator is an iterable protocol to follow. Any call to next() is called an iterator protocol

We made an untraversable data structure traversable as follows:

In fact, the above code can be modified with generator function, the code is as follows

Iterator iterator

The Iterator traverses like this.

  1. Creates a pointer object that points to the start of the current data structure. That is, the traverser object is essentially a pointer object.
  2. The first time a pointer object is callednextMethod to point to the first member of a data structure.
  3. The second call to the pointer objectnextMethod, which points to the second member of the data structure.
  4. That constantly calls the pointer objectnextMethod until it points to the end of the data structure.

Each time the next method is called, information about the current member of the data structure is returned. Specifically, it returns an object containing both the value and done attributes. Where, the value attribute is the value of the current member, and the done attribute is a Boolean value indicating whether the traversal is complete.