3
\$\begingroup\$

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
        }
    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Often, in functional programming, it is actually easier and more useful to write an infinite iterator, and let the user choose how many elements to take. For example, your iterator does not let me write something like "print out the first hundred primes" because I don't know how many non-primes there are between the first hundred primes, and thus I don't know what to pass for size. \$\endgroup\$ Commented Jan 26, 2022 at 8:00
  • \$\begingroup\$ This may be because of the choice of my algorithm. I basically don’t know a better suited algorithm for a stream based implementation of prime generation. (didn’t research it, though) \$\endgroup\$
    – thst
    Commented Jan 26, 2022 at 9:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.