concept

Iterator is an interface type added to ES6 that provides a unified access traversal mechanism for data structures representing the concepts of Array, Object, Map, Set, NodeList, arguments. Therefore, its role mainly includes three aspects: 1. It provides a unified access mechanism for the data structure of the set concept; 2. Arrange the members of the data structure in a certain order; 3. For ES6… Of traversal mechanism consumption. In short, it is an ordered, continuous, pull-based organization for consuming data, that is, a structured data schema for extracting data from sources one at a time.

interface Iterable {
  [Symbol.iterator] (): Iterator } interface Iterator { next (value? : any): IterationResultreturn()? : IterationResultthrow()? : IterationResult } interface IterationResult {value: any
  done: boolean
}

// Connect the Object to Iterator
const iteratorObject = {
  name: 'Iterator'.target: 'ES6'.keyIndex: 0[Symbol.iterator] () {
  	return this;
  },
  next () {
  	const keys = Object.keys(this);
    const len = keys.length;
    return {
      value: this[keys[this.keyIndex]],
      done: this.keyIndex++ >= len }; }};Copy the code

Execute for (const itValue of iteratorObject) {console.log(itValue); } the result is as follows:

Iterator protocol

An iterator is a disposable object used to iterate over the iterable associated with it, which is a data structure of collection type. Each time the iterator calls the Next API, it returns an IterationResult object, where value indicates the value of the iterator and done indicates whether the iteration is exhausted. The iterator is not bound to a snapshot of the iterable at any point in time, but records the progress of the iterable through a pointer. That is, if the iteration object changes during the iteration, the changes will also be reflected during the iteration.

const itArray = ['ES6'.'ES8'.'ES9'];
const it = itArray[Symbol.iterator]();

console.log(it.next());

itArray.splice(1.0.'ES7');
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
Copy the code

The log result is as follows:

ES6Prescribed, by defaultIteratorThe interface is deployed in the data structureSymbol.iteratorOn the property. Among them, native hasIteratorThe data structure of the interface is as follows:

const itMap = new Map([['name'.'Iterator'],
  ['target'.'ES6'],
  ['module'.'Web']]);const it = itMap[Symbol.iterator]();

console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
Copy the code

Custom iterators

Any object with the Iterator interface deployed can be used as an Iterator.

class ItClass {
  constructor (limit) {
  	this.limit = limit;
  }
  
  [Symbol.iterator] () {
    let count = 0;
  	return {
      next () {
      	return {value: count, done: count++ >= this.limit}; }}; }}Copy the code

The above class deploys the Iterator interface, instantiating objects that are iterable. We know that an Object does not deploy an Iterator interface, because it is not a linear traversable structure and cannot determine the order of its attributes. Therefore, to deploy an Iterator interface for an Object is to implement a set of linear conversion functions for it.

Exception handling of iterators

Iterator interface return(…) And throw (…). Are optional interfaces that most iterators do not implement. Among them, the return (…). Used to inform the logic to be performed when the iterator is closed prematurely, such as cleanup work, etc. throw(…) Used to report an exception/error to an iterator, and the iterator does the corresponding processing for that signal, usually exception handling. In general, iterators in return(…) Or throw (…). No value is generated after that.

class itThrowClass {
  constructor (limit) {
  	this.limit = limit;
  }
  
  [Symbol.iterator] () {
    let count = 0;
  	return {
      next () {
      	return {value: count, done: count++ >= this.limit};
      },
      return () {
      	return {done: true};
      },
      throw () {
      	throw new Error('it error'); }}; }}Copy the code