Generators In JS
Generator function are defined with keyword function*
Let’s take below example
function createCounter() {
let count = 0;
// console.log("Counter Init");
return function() {
count++;
// console.log("Return Count:", count);
return count;
}
}
let counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Now there is another way to do the same using generator
function* createCounter() {
let count = 0;
while(true) {
yield ++count;
}
}
let counter = createCounter();
console.log(counter.next().value); //1
console.log(counter.next().value); //2
console.log(counter.next().value); //3