Created
August 18, 2017 04:26
-
-
Save DadgadCafe/b45143544d3d4a06ebc1c812b1ab35ab to your computer and use it in GitHub Desktop.
naive prototype of coroutine
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 _go(g, step) { | |
while(!step.done) { | |
//run the closure function | |
const [state, value] = step.value() | |
switch (state) { | |
case "park": | |
// just wait, add to eventloop | |
// setImmediate(function() { _go(g, step) }) | |
setTimeout(function() { _go(g, step) }) | |
return | |
case "continue": | |
// continue until park | |
step = g.next(value) | |
break | |
} | |
} | |
} | |
function go(gen) { | |
const g = gen() | |
// g.next is hof put or take | |
_go(g, g.next()) | |
} | |
function put(c, val) { | |
return function() { | |
if(c.length == 0) { | |
// pre-append FILO | |
c.unshift(val) | |
return ["continue", null] | |
} | |
return ["park", null] | |
} | |
} | |
function take(chan) { | |
return function() { | |
if(chan.length == 0) { | |
return ["park", null] | |
} | |
// take until chan empty | |
const val = chan.pop() | |
return ["continue", val] | |
} | |
} | |
// def the channel | |
const c = [] | |
// recursively, put one and get one | |
go(function * () { | |
for (let i = 0; i < 10; i++) { | |
yield put(c, i) | |
console.log('put: ', i) | |
} | |
yield put(c, null) | |
}) | |
go(function * () { | |
while (true) { | |
const val = yield take(c) | |
if(val == null) { | |
console.log('nothing more') | |
return | |
} | |
console.log('take: ', val) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment