Generators

 Generators


Generators are functions that can be paused and resumed. They allow you to generate a series of values over time, which is useful for dealing with asynchronous operations or iterating over large datasets.



function* generateNumbers() {

  let i = 0;

  while (true) {

    yield i++;

  }

}


const numberGenerator = generateNumbers();

console.log(numberGenerator.next().value); // Output: 0

console.log(numberGenerator.next().value); // Output: 1

console.log(numberGenerator.next().value); // Output: 2

The generateNumbers generator function uses the yield keyword to produce a series of numbers. Each time you call numberGenerator.next(), it returns an object with the value property containing the next generated value.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...