Skip to content

Instantly share code, notes, and snippets.

@Floofies
Last active July 31, 2018 23:19
Show Gist options
  • Save Floofies/c6bb29563d693b8f5488e807273e28f5 to your computer and use it in GitHub Desktop.
Save Floofies/c6bb29563d693b8f5488e807273e28f5 to your computer and use it in GitHub Desktop.
Showing possible semantics of transforming regular subroutines into coroutines.
// Original source code supplied by userland
function userFunc() {
var one = 1;
var two = 2;
var three = one + two;
return three;
}
// Same source code after compiling with HertzScript
const yieldSym = Symbol("HzYield");
function hzYield(value = yieldSym) {
return {
type: yieldSym,
noValue: value === yieldSym,
value: value
};
}
const returnSym = Symbol("HzReturn");
function hzReturn(value = returnSym) {
return {
type: returnSym,
noValue: value === returnSym,
value: value
}
}
function generatorFunc() {
var hzLoc = 0;
const state = {};
function userFunc() {
switch (hzLoc) {
case 0:
state.one = 1;
hzLoc++;
return hzYield();
case 1:
state.two = 2;
hzLoc++;
return hzYield();
case 2:
state.three = state.one + state.two;
return hzReturn(state.three);
}
return hzReturn();
}
var done = false;
return {
next: function() {
if (done) return {done: true, value: undefined};
var hzValue = userFunc();
if (hzValue.type === returnSym) done = true;
return {
done: done,
value: hzValue.noValue ? undefined : hzValue.value
};
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment