Generators and Iterators

 Generators and Iterators


Generators and iterators can work together to create custom iterable objects.



function* generateSequence(start, end) {

  for (let i = start; i <= end; i++) {

    yield i;

  }

}


const sequence = generateSequence(1, 5);


for (const value of sequence) {

  console.log(value);

}

// Output: 1, 2, 3, 4, 5

In the example above, the generateSequence function is a generator function that produces a sequence of numbers between start and end. The yield keyword is used to pause and resume the execution of the generator, allowing iteration over the generated values.

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...