Last active
July 31, 2018 23:19
-
-
Save Floofies/c6bb29563d693b8f5488e807273e28f5 to your computer and use it in GitHub Desktop.
Showing possible semantics of transforming regular subroutines into coroutines.
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
// 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