Generate While Condition Is Met

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to create a generator function in JavaScript that produces new values while a given condition is met. We will use the generateWhile function which takes in a seed value, a condition function, and a next function to calculate the next value from the current value and the next seed. By the end of this lab, you will be able to create custom generators that can be used to produce values based on specific conditions and rules.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic 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`") subgraph Lab Skills javascript/variables -.-> lab-28347{{"`Generate While Condition Is Met`"}} javascript/data_types -.-> lab-28347{{"`Generate While Condition Is Met`"}} javascript/arith_ops -.-> lab-28347{{"`Generate While Condition Is Met`"}} javascript/loops -.-> lab-28347{{"`Generate While Condition Is Met`"}} end

Generator That Produces Values While a Condition is True

To start coding, open the Terminal/SSH and type node. This will create a generator that keeps producing new values as long as the given condition is met.

The generator is initialized with a seed value, which is used to initialize the current val. A while loop is then used to iterate while the condition function called with the current val returns true.

The yield keyword is used to return the current val and optionally receive a new seed value, nextSeed. The next function is used to calculate the next value from the current val and the nextSeed.

const generateWhile = function* (seed, condition, next) {
  let val = seed;
  let nextSeed = null;
  while (condition(val)) {
    nextSeed = yield val;
    val = next(val, nextSeed);
  }
  return val;
};

To use the generator, call it with the seed, condition, and next functions. For example, calling [...generateWhile(1, v => v <= 5, v => ++v)] will return [1, 2, 3, 4, 5].

Summary

Congratulations! You have completed the Generate While Condition Is Met lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like