Last active
December 22, 2015 11:29
-
-
Save svieira/6465677 to your computer and use it in GitHub Desktop.
Possible reasons for wanting generator expressions to be generators / coroutines rather than simply iterable iterators. In response to questions from Dominic Denicola in http://domenic.me/2013/09/06/es6-iterators-generators-and-iterables/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Treat generators and coroutines the same | |
* This means we need to treat all generators | |
* as coroutines, rather than the other way around. | |
*/ | |
function *loggingDecorator(gen) { | |
let processed = gen.next(null); | |
while (!processed.done) { | |
console.log("INFO:", processed); | |
let unprocessed = yield processed.value; | |
processed = gen.next(unprocessed); | |
} | |
} | |
/** | |
* A simple echoing coroutine | |
*/ | |
function *EchoServer() { | |
let response = yield null; | |
try { | |
while (true) { | |
response = yield response; | |
} | |
} | |
catch (e) { | |
console.log('Shutting down') | |
} | |
} | |
// Now let's create a generator and a coroutine | |
let genexp = (for (x of [1, 2, 3, 4, 5]) x * 2); | |
let echoServer = EchoServer(); | |
// Prime the coroutine | |
echoServer.next(); // {value: null, done: false} | |
// With the current implementation of generator expressions | |
// loggingDecorator doesn't have to care what it is passed | |
let wrappedGen = loggingDecorator(genexp); | |
for (let item of wrappedGen) { | |
console.log('From for loop:', item); | |
// INFO: {value: 2, done: false} | |
// From for loop: 2 | |
// INFO: {value: 4, done: false} | |
// From for loop: 4 | |
// etc. | |
} | |
let wrappedCo = loggingDecorator(echoServer); | |
for (let item of [1, 2, 3, 4, 5]) { | |
item = wrappedCo.next(item); | |
console.log('From for loop:', item); | |
// INFO: {value: 1, done: false} | |
// From for loop: 1 | |
// etc. | |
} | |
// Now give everything a chance to shut down | |
// We don't need to worry about what we were provided | |
// Generators will simply terminate, while coroutines can | |
// perform any cleanup they need to perform. | |
wrappedGen.throw(new SpecialCleanupException); | |
wrappedCo.throw(new SpecialCleanupException); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment