Created
June 29, 2015 01:17
-
-
Save TGOlson/0e860da9c76a7dc59d69 to your computer and use it in GitHub Desktop.
Infinite list of primes with ES6
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* primeGenerator() { | |
| var n = 2; | |
| while(true) { | |
| if(isPrime(n)) { | |
| yield n; | |
| } | |
| n++; | |
| } | |
| } | |
| function takeFromGenerator(n, gen) { | |
| var xs = []; | |
| for(var i = 0; i < n; i++) { | |
| xs.push(gen.next().value); | |
| } | |
| return xs; | |
| } | |
| function isPrime(n) { | |
| for(var i = 2; i <= Math.sqrt(n); i++) { | |
| if(n % i === 0) { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| takeFromGenerator(10, primeGenerator()); | |
| // => [2,3,5,7,11,13,17,19,23,29] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment