Skip to content

Instantly share code, notes, and snippets.

@geastwood
Created June 25, 2014 15:25
Show Gist options
  • Save geastwood/cec809faa36c62627173 to your computer and use it in GitHub Desktop.
Save geastwood/cec809faa36c62627173 to your computer and use it in GitHub Desktop.

Generate take-away

Concept 1: Iterators

In computer programming, an iterator is an object that enables a programmer to traverse a container.

When invoked, generator functions return iterators

Concept 2: Run-to-completion

Run-to-completion scheduling is a scheduling model in which each task runs until it either finishes, or explicitly yields control back to the scheduler.

Generator functions are special functions that return iterators and are denoted using the function* syntax.

function* helloWorldGenerator() {
    yield 'hello';
    yield 'world';
}

var hw = helloWorldGenerator();
console.log(hw.next()); // log {value: 'hello', done: 'false'}
console.log(hw.next()); // log {value: 'world', done: 'false'}
console.log(hw.next()); // log {value: undefined, done: 'false'}

When invoking .next() on the iterator, which causes the generator body to run up until the first yield expression. This expression 'yields' first value, hello and suspends execution of the generator body until .next() is called again. Meanwhile, hw.next() evaluates to a nextResult object, which contains the yielded value and a done flag indicating whether or not there are more values.

Use cases

function* powersOfTwo(maxExponent) {
    var exponent = 0;
    while (exponent <= maxExponent) {
        yield Math.pow(2, exponent);
        exponent++;
    } 
}
var it = powersOfTwo(10), rst = it.next();
while (!result.done) {
    console.log(result.value);
    result = lt.next();
}

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment