Skip to content

Instantly share code, notes, and snippets.

@benlesh
Created March 30, 2015 17:32
Show Gist options
  • Save benlesh/ab8517a54b3e39b196ae to your computer and use it in GitHub Desktop.
Save benlesh/ab8517a54b3e39b196ae to your computer and use it in GitHub Desktop.
Generator Return Values are Weird
window.console.clear();
function* gen1() {
yield 1;
yield 2;
return 3;
}
function printForOf(iter) {
for(var x of iter) {
console.log(x);
}
}
function printTilDone(iter) {
var result;
while(true) {
result = iter.next();
console.log(result);
if(result.done) {
return;
}
}
}
printForOf(gen1());
// 1
// 2
printTilDone(gen1());
// { value: 1, done: false }
// { value: 2, done: false }
// { value: 3, done: true }
/**
* what about merging two?
* */
function* gen2() {
yield 'a';
yield 'b';
return 'c';
}
function* concat(...iters) {
for(let iter of iters) {
for(let x of iter) {
yield x;
}
}
}
printForOf(concat(gen1(), gen2()));
// 1
// 2
// a
// b
/**
* but what to do with the returns? meh.
* */
function* otherConcat(...iters) {
var returnCollection = [];
for(let iter of iters) {
while(true) {
let result = iter.next();
if(result.done) {
// What do I do here? Collect them? Why?
// what if one of them doesn't have a return value?
// I just use `undefined`?
returnCollection.push(result.value);
break;
} else {
yield result.value;
}
}
}
return returnCollection;
}
printForOf(otherConcat(gen1(), gen2()));
// 1
// 2
// 'a'
// 'b'
printTilDone(otherConcat(gen1(), gen2()));
// { value: 1, done: false }
// { value: 2, done: false }
// { value: 'a', done: false }
// { value: 'b', done: false }
// { value: [3, 'c'], done: true }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment