Skip to content

Instantly share code, notes, and snippets.

@mehmetsefabalik
Created July 24, 2018 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mehmetsefabalik/5407a7e4dcb7b3c1b059bbf0f38feb85 to your computer and use it in GitHub Desktop.
Save mehmetsefabalik/5407a7e4dcb7b3c1b059bbf0f38feb85 to your computer and use it in GitHub Desktop.
Javascript Generators and Iterators
// Iterators
const alpha = ['a','b','c'];
const it = alpha[Symbol.iterator]();
it.next(); //{ value: 'a', done: false }
it.next(); //{ value: 'b', done: false }
it.next(); //{ value: 'c', done: false }
it.next(); //{ value: undefined, done: true }
// Generate Fibonacci Sequence using Generator Function
function *fibGen() {
let current = 0;
let next = 1;
while(true) {
yield current;
let nextNum = current + next;
current = next;
next = nextNum;
}
}
let it = fibGen();
it.next().value; //0
it.next().value; //1
it.next().value; //1
it.next().value; //2
// Generator function
function* foo() {
yield 'a';
yield 'b';
yield 'c';
}
for (const val of foo()) {
console.log(val);
}
// a
// b
// c
const [...values] = foo();
console.log(values); // ['a','b','c']
// Communication with Generators
function* crossBridge() {
const reply = yield 'What is your favorite color?';
console.log(reply);
if (reply !== 'yellow') return 'Wrong!'
return 'You may pass.';
}
{
const iter = crossBridge();
const q = iter.next().value; // Iterator yields question
console.log(q);
const a = iter.next('blue').value; // Pass reply back into generator
console.log(a);
}
// What is your favorite color?
// blue
// Wrong!
{
const iter = crossBridge();
const q = iter.next().value;
console.log(q);
const a = iter.next('yellow').value;
console.log(a);
}
// What is your favorite color?
// yellow
// You may pass.
// Generators + Promises
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment