This is an implementation of a Sieve of Eratosthenes as [Symbol.iterator] in JavaScript.
Comments welcome, my JS is a bit rusty. Making a class of this is mainly the reason to have fun with the iterator. I will build a generator of it next.
UPDATE: inverting the sieve flags removes the need to initialize the array with true
console.log([...new Sieve(30)].join(","));
// prints 2,3,5,7,11,13,17,19,23,29
class Sieve {
constructor(size) {
this.size = size;
}
[Symbol.iterator]() {
let primes = Array(this.size);
let nextPrime = 1;
return {
next() {
// find the next prime, marked by falsy in prime[]
do {
if(++nextPrime >= primes.length) return {done :true};
} while(primes[nextPrime])
// remove the multiples of the prime in the sieve
for(let idx=2; idx*nextPrime < primes.length; idx++) {
primes[idx*nextPrime] = true;
}
return { value: nextPrime };
},
[Symbol.iterator]: this
}
}
}
size
. \$\endgroup\$