Created
January 26, 2019 11:15
-
-
Save annibuliful/9b81d531045e7a245646d629ede2e31c 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
| class Observer { | |
| constructor() { | |
| // store of subscribers | |
| this.observers = []; | |
| } | |
| subscribe(aFunction) { | |
| this.observers.push(aFunction); | |
| } | |
| broadcast(data) { | |
| this.observers.forEach(func => { | |
| func(data); | |
| console.log("\n"); | |
| }); | |
| } | |
| } | |
| let posts = []; | |
| const Ob = new Observer(); | |
| const subscriberOne = data => { | |
| console.log("From function One, Data:", data); | |
| posts.push(data); | |
| }; | |
| const subscriberTwo = data => { | |
| console.log("From function Two, Data: ", data); | |
| console.log(posts); | |
| }; | |
| Ob.subscribe(subscriberOne); | |
| Ob.subscribe(subscriberTwo); | |
| setInterval(() => { | |
| Ob.broadcast(Math.random()); | |
| }, 500); | |
| class Iterator { | |
| constructor() { | |
| this.currentIndex = 0; | |
| this.listPosts = ["Somsri", "Somchai", "Sommai", "Manee", "Manah"]; | |
| } | |
| first() { | |
| this.reset(); | |
| return this.listPosts[this.currentIndex]; | |
| } | |
| next() { | |
| return this.listPosts[this.currentIndex++]; | |
| } | |
| reset() { | |
| this.currentIndex = 0; | |
| } | |
| } | |
| const Iter = new Iterator(); | |
| console.log(Iter.first()); | |
| console.log(Iter.next()); | |
| console.log(Iter.next()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment