Creating Infinite Iterators
Explore how to create infinite iterators in JavaScript using generator functions. Understand lazy evaluation to generate prime numbers on demand, yielding values efficiently without storing large sequences in memory. Learn to control iterations and apply these concepts for more effective coding.
Iterators in JavaScript are inherently lazy. They yield a value, wait for it to be consumed by the caller, and then, when requested for more, go on to produce the next value. While we can yield values from a known collection of data, we can also exploit this flexibility to create infinite sequences of data.
Creating an infinite sequence of prime numbers
As an example, let’s create an infinite sequence of prime numbers.
As a first step, we’ll define an isPrime() function that will tell us whether a given number is a prime number.
The isPrime() ...