Created
December 15, 2015 17:56
-
-
Save tgraham777/665fa7319fa786537e43 to your computer and use it in GitHub Desktop.
Remote day work - recursion and generators in 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
| function countdown(n) { | |
| if (n >= 1) { | |
| console.log(n); | |
| countdown(n-1); | |
| } | |
| } | |
| countdown(5); |
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 i = 2; | |
| var fib = [1, 1]; | |
| function fibonacci(n) { | |
| if (i < n) { | |
| fib[i] = fib[i-2] + fib[i-1]; | |
| i++; | |
| fibonacci(n); | |
| } else { | |
| console.log(fib); | |
| } | |
| } | |
| fibonacci(10); |
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
| function* factorialGenerator() { | |
| var count = 1; | |
| var i = 1; | |
| while (true) { | |
| if (count > 0) { | |
| i = i * count; | |
| count++; | |
| } | |
| yield i; | |
| } | |
| } | |
| var factorial = factorialGenerator(); | |
| console.log(factorial.next().value); | |
| console.log(factorial.next().value); | |
| console.log(factorial.next().value); | |
| console.log(factorial.next().value); | |
| console.log(factorial.next().value); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment