Case Analysis of JavaScript Design Model Iterator
This article mainly introduces the relevant knowledge of JavaScript design model Iterator case analysis, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this JavaScript design model Iterator case analysis article. Let's take a look.
The main things of Iterator are two: hasNext and next. Let Client know if there is another one, and switch to the next one!
Define Interface
Interface IteratorInterface {index: number dataStorage: any hasNext (): boolean next (): any addItem (item: any): void}
Implementation interface
In the following example, I will use two common interfaces, Map and Array, to implement.
Class iterator1 implements IteratorInterface {index: number dataStorage: any [] constructor () {this.index = 0 this.dataStorage = []} hasNext (): boolean {return this.dataStorage.length > this.index} next (): any {return this.dataStorage [this.index + +]} addItem (item: any): void {this.dataStorage.push (item)}} / / mapclass iterator2 implements IteratorInterface {index: number dataStorage: Map constructor () { This.index = 0 this.dataStorage = new Map ()} hasNext (): boolean {return this.dataStorage.get (this.index)! = undefined} next (): any {return this.dataStorage.get (this.index + +)} addItem (item: any): void {this.dataStorage.set (this.dataStorage.size) Item)}}
Client
I did not implement a Client, so I am directly new a category out of direct use!
Const I = new iterator1 () i.addItem (123) i.addItem (456) i.addItem ('dolphin') while (i.hasNext ()) {console.log (i.next ())} console.log (`=`) const i2 = new iterator2 () i2.addItem (123) i2.addItem (456) i2.addItem (' dolphin') while (i2.hasNext ()) {console.log (i2.next ())} on "Iterator case Analysis of JavaScript Design Model" Thank you for reading! I believe you all have a certain understanding of the knowledge of "Iterator case Analysis of JavaScript Design Model". If you want to learn more knowledge, you are welcome to follow the industry information channel.