Get the App
SLTechnology News&Howtos  ›  Development  › 

How to carry on the practice of JavaScript Design Model Iterator

Shulou Source: shulou.com Published: 2022-06-03 08:06:16 09月18日 Update

Today, I will talk to you about the practice of how to carry out the JavaScript design model Iterator. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.

Hands-on Iterator Pattern is a very important and simple Pattern: iterator!

We can provide an iterator with a unified entry. Client only needs to know what methods or Concrete Iterator are available, not how they are implemented at the bottom!

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: Mapconstructor () { 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, 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 ())}

You will find that the results of Iterator No.1 and No.2 are all the same! They all just need to let Client know that there is hasNext and next, and the underlying implementation does not need to let them know!

After reading the above, do you have any further understanding of how to practice the JavaScript design model Iterator? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Tags: Content model practice design two interface underlying iteration important thing entrance that is common method more knowledge article category result example Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Apple Redmi Shulou Tech Info Shulou Technology