Skip to content

Instantly share code, notes, and snippets.

@Floofies
Last active July 31, 2018 23:20
Show Gist options
  • Save Floofies/9f68ce0ecddc6e76e8fb260b4529cdad to your computer and use it in GitHub Desktop.
Save Floofies/9f68ce0ecddc6e76e8fb260b4529cdad to your computer and use it in GitHub Desktop.
An example of coroutines and a simple coroutine scheduler.
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