loading
open in
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Generator to calculate prime numbers
function* primeNumbers() { 
  let n = 2;

  while (true) {
    if (isPrime(n)) yield n;
    n++;
  }

  function isPrime(num) {
    for (let i = 2; i <= Math.sqrt(num); i++) {
      if (num % i === 0) {
        return false;
      }
    }
    return true;
  }
}

// Create generator
var primeGenerator = primeNumbers();
// Advance through generator with next(), print out value
console.log(primeGenerator.next().value);
console.log(primeGenerator.next().value);
console.log(primeGenerator.next().value);
console.log(primeGenerator.next().value);
console.log(primeGenerator.next().value);
// Calls to primerGenerator.next() returns infinite prime numbers

Native Browser JavaScript