In computer programming, an iterator is an object that enables a programmer to traverse a container.
When invoked, generator functions return iterators
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.
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();
}