Skip to content

Instantly share code, notes, and snippets.

@hkoba
Last active July 24, 2021 08:16
Show Gist options
  • Save hkoba/5d064f9440773f876d5654e8ef71687d to your computer and use it in GitHub Desktop.
Save hkoba/5d064f9440773f876d5654e8ef71687d to your computer and use it in GitHub Desktop.
To pass JS Generator between functions like stream, you should not use `for (const v of gen)`
console.log('\nNG')
ng();
console.log('\nOK')
ok();
function ng() {
let lex = gen(0, 10);
for (const i of lex) {
console.log(`top: ${i}`)
if (i === 3) {
scan1(lex)
}
}
}
function scan1(lex: Generator<number>) {
for (const i of lex) {
console.log(`scan1: ${i}`)
if (i === 5) {
scan2(lex)
}
}
}
function scan2(lex: Generator<number>) {
for (const i of lex) {
console.log(`scan2: ${i}`)
if (i === 7)
return;
}
}
function ok() {
let lex = gen(0, 10);
let cur;
while (!(cur = lex.next()).done) {
const i = cur.value
console.log(`top: ${i}`)
if (i === 3) {
ok_scan1(lex)
}
}
}
function ok_scan1(lex: Generator<number>) {
let cur;
while (!(cur = lex.next()).done) {
const i = cur.value
console.log(`scan1: ${i}`)
if (i === 5) {
ok_scan2(lex)
}
}
}
function ok_scan2(lex: Generator<number>) {
let cur;
while (!(cur = lex.next()).done) {
const i = cur.value
console.log(`scan2: ${i}`)
if (i === 7)
return;
}
}
NG
top: 0
top: 1
top: 2
top: 3
scan1: 4
scan1: 5
scan2: 6
scan2: 7
OK
top: 0
top: 1
top: 2
top: 3
scan1: 4
scan1: 5
scan2: 6
scan2: 7
scan1: 8
scan1: 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment