function* zeros() { while (true) { yield 0; } } function* map(callback) { for (const x of this) { yield callback(x); } } function* accumulate(callback, initial = 0) { let result = initial; for (const x of this) { result = callback(result, x); yield result; } } function* ones() { yield* Reflect.apply(map, zeros(), [x => x + 1]); } function* positive_integers() { yield* Reflect.apply(accumulate, ones(), [(x, y) => x + y]); } function* slice(count) { for (const x of this) { if (count > 0) { --count; } else { yield x; } } } const primes_list = []; function* primes() { for (const n of Reflect.apply(slice, positive_integers(), [1])) { let is_prime = true; for (const p of primes_list) { if (p * p > n) { break; } else if (n % p === 0) { is_prime = false; break; } } if (is_prime) { primes_list.push(n); yield n; } } } for (const n of primes()) { if (n > 10000) { break; } else { console.log(`${n} is a prime`); } }