Skip to content

Instantly share code, notes, and snippets.

@TGOlson
Created June 29, 2015 01:17
Show Gist options
  • Select an option

  • Save TGOlson/0e860da9c76a7dc59d69 to your computer and use it in GitHub Desktop.

Select an option

Save TGOlson/0e860da9c76a7dc59d69 to your computer and use it in GitHub Desktop.
Infinite list of primes with ES6
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