Skip to content

Instantly share code, notes, and snippets.

@barenko
Created June 16, 2023 19:45
Show Gist options
  • Save barenko/5cb16d929c0116946d0548c8d0fd429f to your computer and use it in GitHub Desktop.
Save barenko/5cb16d929c0116946d0548c8d0fd429f to your computer and use it in GitHub Desktop.
Example of javascript generator flow
g = function*(){
console.log('\tstarted')
while(true){
console.log('\tloop')
const res = yield //get next variable and put in res
console.log('\t', res, '= yield')
console.log('\tyield', 'V'+res)
yield 'V'+res //get 'V'+res and return to caller in {value:'V'+res, done:false} format
}
}
//initialize
gg = g()
//pass data
r = gg.next(1)
console.log(JSON.stringify(r), " = gg.next(1)")
//[Log] started
//[Log] loop
//[Log] {"done":false} – " = gg.next(1)"
r = gg.next(2)
gg.next()
console.log(JSON.stringify(r), " = gg.next(2)")
//[Log] – 2 – "= yield"
//[Log] yield – "V2"
//[Log] loop
//[Log] {"value":"V2","done":false} – " = gg.next(2)"
r = gg.next(3)
gg.next()
console.log(JSON.stringify(r), " = gg.next(3)")
//[Log] – 3 – "= yield"
//[Log] yield – "V3"
//[Log] loop
//[Log] {"value":"V3","done":false} – " = gg.next(3)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment