Generating Range Values with JavaScript Generators

Beginner

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

Introduction

In this lab, we will explore how to create a rangeGenerator function in JavaScript that generates all values in a given range using a specified step. We will use a while loop and the yield keyword to return each value and increment by the specified step. By the end of this lab, you will have a better understanding of how to create custom generators in JavaScript and their practical applications.

Range Generator

To generate a range of values using a given step, use the following rangeGenerator function. Open the Terminal/SSH and type node to start coding.

  • Use a while loop and yield to return each value, starting from start and ending at end.
  • If you want to use a default step of 1, omit the third argument.
const rangeGenerator = function* (start, end, step = 1) {
  let i = start;
  while (i < end) {
    yield i;
    i += step;
  }
};

Here's an example of how to use the rangeGenerator function:

for (let i of rangeGenerator(6, 10)) console.log(i);
// Logs 6, 7, 8, 9

Summary

Congratulations! You have completed the Range Generator lab. You can practice more labs in LabEx to improve your skills.