Created
March 16, 2018 08:45
-
-
Save RANUX/809a958b8dca83f81c75d7324fc3af0d to your computer and use it in GitHub Desktop.
Fibonaci and factorial iterators on JavaScript
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
| var Fib = { | |
| [Symbol.iterator]() { | |
| var n1 = 1, n2 = 1; | |
| return { | |
| // make the iterator an iterable | |
| [Symbol.iterator]() { return this; }, | |
| next() { | |
| var current = n2; | |
| n2 = n1; | |
| n1 = n1 + current; | |
| return { value: current, done: false }; | |
| }, | |
| return(v) { | |
| console.log( | |
| "Fibonacci sequence abandoned." | |
| ); | |
| return { value: v, done: true }; | |
| } | |
| }; | |
| } | |
| }; | |
| var Fact = { | |
| [Symbol.iterator]() { | |
| var n1 = 1, n2 = 1; | |
| return { | |
| [Symbol.iterator]() { return this; }, | |
| next() { | |
| var current = n1; | |
| n2 += 1; | |
| n1 = n2 * current; | |
| return { value: current, done: false }; | |
| }, | |
| return(v) { | |
| console.log( | |
| "Factorial sequence abandoned." | |
| ); | |
| return { value: v, done: true }; | |
| } | |
| }; | |
| } | |
| }; | |
| for (var v of Fact) { | |
| console.log( v ); | |
| if (v > 10000) break; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment