Created
August 11, 2024 06:38
-
-
Save BiosBoy/f0642efba971c171ae2bfe7149108440 to your computer and use it in GitHub Desktop.
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
function* simpleGenerator() { | |
console.log("First execution"); | |
yield 1; | |
console.log("Second execution"); | |
yield 2; | |
console.log("Third execution"); | |
} | |
const gen = simpleGenerator(); | |
console.log(gen.next()); // { value: 1, done: false } | |
console.log(gen.next()); // { value: 2, done: false } | |
console.log(gen.next()); // { value: undefined, done: true } | |
function* infiniteSequence() { | |
let i = 0; | |
while (true) { | |
yield i++; | |
} | |
} | |
const seq = infiniteSequence(); | |
console.log(seq.next().value); // 0 | |
console.log(seq.next().value); // 1 | |
console.log(seq.next().value); // 2 | |
function* asyncFlow() { | |
const data = yield fetchDataFromAPI(); | |
console.log(data); | |
} | |
const iterator = asyncFlow(); | |
iterator.next().value.then((data) => { | |
iterator.next(data); | |
}); | |
function* stateMachine() { | |
while (true) { | |
const state = yield; | |
switch (state) { | |
case "START": | |
console.log("Starting"); | |
break; | |
case "PAUSE": | |
console.log("Pausing"); | |
break; | |
case "STOP": | |
console.log("Stopping"); | |
return; | |
} | |
} | |
} | |
const machine = stateMachine(); | |
machine.next(); // Initialize the generator | |
machine.next("START"); // Starting | |
machine.next("PAUSE"); // Pausing | |
machine.next("STOP"); // Stopping | |
function* typedGenerator(): Generator<number, void, unknown> { | |
yield 1; | |
yield 2; | |
yield 3; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment