Skip to content

Instantly share code, notes, and snippets.

@forabi
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forabi/304f881d89aeb14fb175 to your computer and use it in GitHub Desktop.
Save forabi/304f881d89aeb14fb175 to your computer and use it in GitHub Desktop.
ECMAScript 6 implementation of Sieve of Eratosthenes algorithm https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
'use strict';
function* getPrimes(n) {
let compos = [];
for (let i = 2; i <= n; i++) {
if (compos[i]) continue;
yield i;
for (let j = i * 2; j <= n; j += i) {
compos[j] = true;
}
}
}
function toArray(iterator) {
// Using array comprehensions (not supported in node v0.11.23):
// return [prime for (prime of iterator)];
let array = [];
for (let prime of iterator) {
array.push(prime);
}
return array;
}
function print(n) {
for (let prime of getPrimes(n)) {
console.log(prime);
}
}
function benchmark(n, iterations) {
let start = new Date;
for (let j = 0; j < iterations; j++) {
toArray(getPrimes(n));
}
return new Date - start;
}
console.log(benchmark(10000, 500));
// print(10000000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment