Created
June 8, 2019 16:20
-
-
Save annibuliful/d53dd250952062a95a3227368abb6157 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const Observable = require('./observer'); | |
| const Iterator = require('./iterator'); | |
| const observer = new Observable(); | |
| const iterator = new Iterator(); | |
| observer.subscribe((data)=>{ | |
| console.log("Listener 1", data); | |
| console.log(""); | |
| }) | |
| observer.subscribe((data)=>{ | |
| console.log("Listener 2", data); | |
| console.log(""); | |
| }) | |
| iterator.add(`Hello ${Math.random()}`); | |
| iterator.add(`Hello ${Math.random()}`); | |
| iterator.add(`Hello ${Math.random()}`); | |
| iterator.add(`Hello ${Math.random()}`); | |
| iterator.add(`Hello ${Math.random()}`); | |
| iterator.add(`Hello ${Math.random()}`); | |
| setInterval(()=>{ | |
| const result = iterator.next(); | |
| if(result !== -1){ | |
| observer.emit(result); | |
| }else{ | |
| console.log('there is no contain data'); | |
| } | |
| },1000); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module.exports = class Iterator { | |
| constructor(){ | |
| this.data = []; | |
| this.currentIndex = 0; | |
| } | |
| add(data){ | |
| this.data.push(data); | |
| } | |
| hasNext(){ | |
| return this.currentIndex === this.data.length; | |
| } | |
| next(){ | |
| if(!this.hasNext()){ | |
| const result = this.data[this.currentIndex]; | |
| this.currentIndex++; | |
| return result; | |
| } | |
| return -1; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module.exports = class Observable { | |
| constructor(){ | |
| this.listObservers = []; | |
| } | |
| subscribe(func){ | |
| this.listObservers.push(func); | |
| } | |
| emit(data){ | |
| this.listObservers.forEach((func)=> func(data)); | |
| } | |
| unsubscribe(func){ | |
| this.listObservers = this.listObservers.filter((observFunction)=> observFunction !== func); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment