Here’s another example taken from the narrative of “The Sieve of Eratosthenes” (a Pro offering, I believe, so you may not be able to access it). Note the return value…
const sieveOfEratosthenes = (limit) => {
// Handle edge cases
if (limit <= 1) {
return [];
}
// Create the output
const output = new Array(limit + 1).fill(true);
// Mark 0 and 1 as non-prime
output[0] = false;
output[1] = false;
// Iterate up to the square root of the limit
for (let i = 2; i < Math.pow(limit, 0.5); i++) {
if (output[i] === true) {
// Mark all multiples of i as non-prime
for (let j = Math.pow(i, 2); j <= limit; j = j + i) {
output[j] = false;
}
}
}
// Remove non-prime numbers
return output.reduce((primes, current, index) => {
if (current) {
primes.push(index);
}
return primes
}, []);
}
Above we have an array of truth values, either true or false that has be sieved over and transformed from all true, to only some true (the ones that don’t get re-marked). In the return expression we cache only the indices where the value is true. That gives us our list of primes up to the limit.