Exploring JavaScript Generators: Cyclic Array Iteration

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28234{{"`Exploring JavaScript Generators: Cyclic Array Iteration`"}} javascript/data_types -.-> lab-28234{{"`Exploring JavaScript Generators: Cyclic Array Iteration`"}} javascript/arith_ops -.-> lab-28234{{"`Exploring JavaScript Generators: Cyclic Array Iteration`"}} javascript/loops -.-> lab-28234{{"`Exploring JavaScript Generators: Cyclic Array Iteration`"}} javascript/destr_assign -.-> lab-28234{{"`Exploring JavaScript Generators: Cyclic Array Iteration`"}} end

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:

  1. Use a non-terminating while loop that will yield a value each time Generator.prototype.next() is called.
  2. Use the module operator (%) with Array.prototype.length to get the next value's index and increment the counter after each yield statement.

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.

Other JavaScript Tutorials you may like