Generating primes in ES6

comment

Generators can be used to represent infinite streams of values. The algorithm used below is the sieve of Eratosthenes. for-of loops are used to iterate over values returned from the generator.

Chrome supports both ES6 generators and for-of loops but it's necessary to enable Experimental JavaScript at chrome://flags/#enable-javascript-harmony (version 36).

Firefox supports generators as well as for-of loops (version 29). To use them with custom objects they need to provide the iterator method. Chrome treats the object passed to for-of loop as an iterator itself and calls next directly.

To run the example your browser has to support:

// change 10 to 15 below and click "Execute"
for (var prime of take(10 /* <--here */, primes())) {
    print(prime);
}

function* primes() {
    var seq = numbers(2);
    var prime;

    while (true) {
        prime = seq.next().value;
        yield prime;
        seq = filter(seq, prime);
    }
}

function* numbers(start) {
    while (true) {
        yield start++;
    }
}

function* take(count, seq) {
    for (var i = 0; i < count; i++) {
        yield seq.next().value;
    }
}

function* filter(seq, prime) {
    for (var num of seq) {
        if (num % prime !== 0) {
            yield num;
        }
    }
}

The same algorithm implemented using channels and goroutines can be found on the go lang example package page.

Comments

cancel

Revisions

  1. Initial version.
  2. Hide scaffolding code (clear/log/print).