Created
November 20, 2020 02:26
-
-
Save nasser/90b1181897c0359491f65be93b0ef2f4 to your computer and use it in GitHub Desktop.
javascript coroutine wrap
This file contains 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
// based on coroutine.wrap in lua (https://www.lua.org/pil/9.3.html) | |
function wrap(generator) { | |
let g = null | |
return function(...args) { | |
if(!g) | |
g = generator(...args) | |
return g.next(...args).value | |
} | |
} | |
// usage | |
var f = wrap(function* (name) { | |
console.log('hello', name); | |
let other = yield name.length | |
console.log('hello', name, other); | |
}) | |
f('ramsey') | |
// prints: hello ramsey | |
// returns: 6 | |
f('nasser') | |
// prints: hello ramsey nasser | |
// returns: undefined | |
f('nasser') | |
// returns: undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment