Skip to content

Instantly share code, notes, and snippets.

@nasser
Created November 20, 2020 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasser/90b1181897c0359491f65be93b0ef2f4 to your computer and use it in GitHub Desktop.
Save nasser/90b1181897c0359491f65be93b0ef2f4 to your computer and use it in GitHub Desktop.
javascript coroutine wrap
// 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