After watching a thought-provoking video on computerphile, I was inspired to try my hand at implementing the sieve algorithm using JavaScript generators. While I have experience with JavaScript, working directly with generators is a new challenge for me.
Here's my current progress:
function* nextNaturalNumber(n) {
yield n;
yield* nextNaturalNumber(n + 1);
}
function* sieve(n) {
let count = 0;
let g = nextNaturalNumber(2);
while (count++ < n) {
const possiblePrime = g.next().value;
yield possiblePrime;
// Here's where I'm encountering an obstacle:
// How can I filter out values from the nextNaturalNumber-generator stream that are not divisible by 2?
}
}
// Display the first 10 prime numbers
for (const prime of sieve(10)) {
console.log(prime);
}
The code-comment indicates my struggle with filtering out values in the generator stream that are not divisible by 2 and achieving the "sieve" operation. Is there a straightforward way to accomplish this task in JavaScript, similar to how it's done in Python with
yield from sieve(i for i in s if i%n !=0)
?