Introduction
In this lab, we will explore the concept of generators in JavaScript and learn how to create a cycle generator that loops over an array indefinitely. We will use the yield keyword and a while loop to create the generator, and then test it with different arrays to see how it works. By the end of this lab, you will have a deeper understanding of generators and how they can be used in your JavaScript projects.
Cycle Generator Instructions
To start practicing coding, open the Terminal/SSH and type node. Afterward, create a generator that loops over the given array indefinitely. Here are the steps:
- Use a non-terminating
whileloop that willyielda value each timeGenerator.prototype.next()is called. - Use the module operator (
%) withArray.prototype.lengthto get the next value's index and increment the counter after eachyieldstatement.
Here's an example of the cycleGenerator function:
const cycleGenerator = function* (arr) {
let i = 0;
while (true) {
yield arr[i % arr.length];
i++;
}
};
You can then use the function as follows:
const binaryCycle = cycleGenerator([0, 1]);
binaryCycle.next(); // { value: 0, done: false }
binaryCycle.next(); // { value: 1, done: false }
binaryCycle.next(); // { value: 0, done: false }
binaryCycle.next(); // { value: 1, done: false }
With these instructions, you can create a cycle generator that loops over any array indefinitely.
Summary
Congratulations! You have completed the Cycle Generator lab. You can practice more labs in LabEx to improve your skills.