es6 generator examples

Official description of generators:
Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.
Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. When the iterator’s next() method is called, the generator function’s body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. The next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value.

Generator examples:

// simple generator function
function* simpleGeneratorFunc() {
	yield 1;
	yield 2;
	return "finished";
}
let gen = simpleGeneratorFunc();
console.log(gen.next());	// { value: 1, done: false }
console.log(gen.next());	// { value: 2, done: false }
console.log(gen.next());	// { value: 'finished', done: true }


// calling generator function inside a generator function
function* callGeneratorInGenerator() {
	yield 'a';
	yield* simpleGeneratorFunc();
	yield 'b';
}
gen = callGeneratorInGenerator();
console.log(gen.next());	// { value: 'a', done: false }
console.log(gen.next());	// { value: 1, done: false }
console.log(gen.next());	// { value: 2, done: false }
console.log(gen.next());	// { value: 'b', done: false }
console.log(gen.next());	// { value: undefined, done: true }

// ways of iterating through all the yields in the generator function

// while loop
gen = simpleGeneratorFunc();
let item = {"done":false};
while(!item.done) {
	item = gen.next();
	console.log(item);
}
// { value: 1, done: false }
// { value: 2, done: false }
// { value: 'finished', done: true }


// for of
for (let g of simpleGeneratorFunc()) {
	console.log(g);
}
//1
//2

// the three dots spread operator ...
let arr = [...simpleGeneratorFunc()];
console.log(arr); // [1, 2]

// destructuring
let [a, b] = simpleGeneratorFunc();
console.log(a); // 1
console.log(b); // 2

Search within Codexpedia

Custom Search

Search the entire web

Custom Search