Last active
June 15, 2020 20:11
-
-
Save evan-brass/d17bcb66f1847c8a79cabdb5c8b9d519 to your computer and use it in GitHub Desktop.
An example of an iterable class
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 Fib { | |
| a = 0; | |
| b = 0; | |
| next() { | |
| if (this.a == 0) { | |
| this.a = 1; | |
| return { value: 1, done: false }; | |
| } | |
| if (this.b == 0) { | |
| this.b = 1; | |
| return { value: 1, done: false }; | |
| } | |
| const value = this.a + this.b; | |
| this.a = this.b; | |
| this.b = value; | |
| return { value, done: false }; | |
| } | |
| [Symbol.iterator]() { | |
| return this; | |
| } | |
| } | |
| for (let n of new Fib()) { | |
| console.log(n); | |
| if (n > 1000) break; | |
| } | |
| /* Output from the above loop: | |
| 1 | |
| 1 | |
| 2 | |
| 3 | |
| .. | |
| 1597 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment