Last active
July 31, 2018 23:20
-
-
Save Floofies/9f68ce0ecddc6e76e8fb260b4529cdad to your computer and use it in GitHub Desktop.
An example of coroutines and a simple coroutine scheduler.
This file contains hidden or 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
function Dispatcher() { | |
this.coroutine = null; | |
this.loc = -1; | |
this.stack = []; | |
} | |
Dispatcher.prototype.run = function* () { | |
var returnValue = null; | |
while (this.loc !== -1) { | |
this.coroutine = stack[loc]; | |
const state = this.coroutine.next(returnValue !== null ? returnValue : undefined); | |
returnValue = null; | |
if (state.done) { | |
this.stack.pop(); | |
this.loc--; | |
} else if (state.type === "return") { | |
returnValue = state.value; | |
this.stack.pop(); | |
this.loc--; | |
} else if (state.type === "call") { | |
this.loc++; | |
this.stack.push(state.functor); | |
} | |
yield; | |
} | |
} | |
Dispatcher.prototype.runSync = function () { | |
const runner = this.run(); | |
while (!runner.next().done); | |
}; | |
Dispatcher.prototype.call = function(coroutune) { | |
this.stack.push(coroutine); | |
} | |
function call(generator, args, thisArg) { | |
return { type: "call", functor: generator.call(thisArg, args) }; | |
} | |
function exit(value = null) { | |
return { type: "yieldVal", value: value }; | |
} | |
function generator1() { | |
var loc = 0; | |
const iterator = { | |
done: false, | |
next: function () { | |
switch (loc) { | |
case 0: | |
console.log("Hello World"); | |
loc++; | |
return iterator; | |
case 1: | |
console.log("Goodbye MoonMan"); | |
loc++; | |
return iterator; | |
case 2: | |
console.log("What's up, doc?"); | |
iterator.done = true; | |
} | |
return iterator; | |
} | |
}; | |
return iterator; | |
} | |
function generator2(returnVal = null) { | |
var loc = 0; | |
const iterator = { | |
done: false, | |
next: function () { | |
switch (loc) { | |
case 0: | |
loc++; | |
return call(generator1); | |
case 1: | |
loc++; | |
return exit("Test"); | |
} | |
iterator.done = true; | |
return iterator; | |
} | |
}; | |
return iterator; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment