Created
August 19, 2020 17:06
-
-
Save nguyendv/b9f9b60b03b704762731418eb4c64e01 to your computer and use it in GitHub Desktop.
js generator
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
// Generators are denoted using `function*` syntax | |
const myGenerator = function* () { | |
console.log("a"); | |
} | |
const iterator = myGenerator(); | |
iterator.next(); // execute the generator's body, which displays "a" | |
// a generator that generates numbers | |
const numberGenerator = function* () { | |
let n = 0; | |
while(true) { | |
yield n; | |
n += 1; | |
if (n === 4) break; | |
} | |
} | |
const numberIter = numberGenerator(); | |
console.log(numberIter.next()) | |
console.log(numberIter.next()) | |
console.log(numberIter.next()) | |
console.log(numberIter.next()) | |
console.log(numberIter.next()) | |
// for...of over an iterator | |
const numberIter2 = numberGenerator(); | |
for (number of numberIter2) { | |
console.log(number); | |
} | |
// delegating yield: yield another generator | |
const foo = function* () { | |
yield 1; | |
yield * bar(); | |
} | |
const bar = function* () { | |
yield 2; | |
} | |
for (item of foo()){ | |
console.log(item); | |
} // output: 1, 2 | |
// iterator can throw values to its generator | |
const myGenerator2 = function* () { | |
try { | |
yield 1 | |
} catch (e) { | |
if (e === 'a') { | |
console.log("caught a"); | |
} else { | |
throw e | |
} | |
} | |
} | |
const myIter2 = myGenerator(); | |
myIter2.throw('a'); // output: caught a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment