I am struggling to make the while loop function correctly within for loops in TypeScript

Looking to obtain an array of arrays with unique values, but running into issues when

while

loop seems to get skipped or overlooked (possibly due to the asynchronous nature of it). Would appreciate assistance in implementing a promise within this code snippet, or utilizing

async/await

methods, or receiving better guidance on how to properly handle these arrays. Attempted adding

async/await

functionality but encountered errors and unsure about where to integrate a promise effectively. The current function is as follows:

getSeveralArrays() {
 for (let index = 0; index < 50; index++) {
        this.getValue();
      }
}
getValue() {

    this.i++;

    this.array = [];
    this.randomArray = [];
for (let index = 0; index < 4; index++) {

    this.randomValue = this.getRandom();

    if (this.array.length === 2) {

        while ((this.array[0] === this.randomValue) || (this.array[1] === this.randomValue)) {
            this.randomValue = this.getRandom();
        }

        this.array.push(this.randomValue);


    } else if (this.array.length === 3) {

        while ((this.array[0] === this.randomValue) || (this.array[1] === this.randomValue) || (this.array[2] === this.randomValue)) {
            this.randomValue = this.getRandom();
        }

        this.array.push(this.randomValue);


    } else {

        this.array.push(this.randomValue);

    }

    console.log({...this.array});

    this.randomArray.push({ind: this.i, val: this.array});

    }
}


  getRandom() {

      const value = Math.floor(Math.random() * 4);
      return value;
  }

Answer №1

Your code does not utilize asynchronous functions, so there is no requirement for async/await. Additionally, the use of while does not introduce asynchronicity.

One flaw in your code was that a case for a length of 1 was missing, causing the second element to always be the same as the first.

class X {
  getSeveralArrays() {
    for (let index = 0; index < 50; index++) {
      this.getValue();
    }
  }
  getValue() {
    this.i++;

    let array = [];
    let randomArray = [];
    for (let index = 0; index < 4; index++) {
      let randomValue = this.getRandom();

      if (array.length === 1) {
        while (array[0] === randomValue) {
          randomValue = this.getRandom();
        }
        array.push(randomValue);
      } else if (array.length === 2) {
        while (array[0] === randomValue || array[1] === randomValue) {
          randomValue = this.getRandom();
        }
        array.push(randomValue);
      } else if (array.length === 3) {
        while (
          array[0] === randomValue ||
          array[1] === randomValue ||
          array[2] === randomValue
        ) {
          randomValue = this.getRandom();
        }
        array.push(randomValue);
      } else {
        array.push(randomValue);
      }

      console.log({ ...array });

      randomArray.push({ ind: this.i, val: array });
    }
  }

  getRandom() {
    const value = Math.floor(Math.random() * 4);
    return value;
  }
}

console.log(new X().getSeveralArrays());

Some simplifications can be made in your checks:

      while (array.some(value => value === randomValue)) {
        randomValue = this.getRandom();
      }

For better practice, consider restricting the scope of variables only when needed outside of the function by defining them with let or const.

Hence, randomValue and array should be declared within the function instead of being class properties.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the most frequently occurring sequence of symbols within a collection of lists is my ultimate goal

I need to identify the most frequent sequence of symbols from the set of [lists] CATEGORIES = [...list of categories...] Problem with iteration is here: print(compare_bitwise(i, i+=1)) I have provided an example of data only in the initial list, as all ot ...

Using underscores instead of spaces for keys in multi-dimensional arrays

I am struggling with an array that has spaces in the keys, which poses a problem when targeting those keys in programs that do not support spaces. It is generally considered bad practice to have spaces in keys. I am searching for a solution to remove the ...

The C# method is receiving a null array through Ajax

When I retrieve an array in a loop and pass it through an ajax call to my C# method, I'm encountering a problem where only null values are being received in my parameter. The count of the array is coming through, but the actual data seems to be lost. ...

Conceal elements depending on the route path in Angular versions 5 and 6

I'm currently overseeing a project in Angular and I encountered an interesting obstacle when attempting to enhance the system. There are certain elements that should not be visible on specific URLs. Is there a method to conceal an element based on th ...

Is there a way to divide v-progress linear into 4 pieces in Vuejs, or are there alternative design options for achieving this in Vuetify 2?

I have set up a table in Vuetify 2 with a v-progress-linear component to monitor the user's remaining time. Initially, my implementation was simple like this. https://i.sstatic.net/x373G.png However, we decided to split it into 4 sections for better ...

Exploring JSON data with Handlebars for creating templates

My JSON data is formatted as follows: { "review": { "count": "1", "summary": [ { "Q1": "9.50", "Q2": "9.50", "Q3": "9.00", "Q4": "8.75", "Q5": ...

Is there a way to extend a formula downwards while skipping certain rows and still have the numbers count sequentially?

I am facing a challenge with my table of product details and the need to create another table suitable for Magento export. If you could take a look at the table here, it would help in understanding the issue: https://docs.google.com/spreadsheets/d/1s503ga ...

Error: Unable to retrieve the value of 'secret' as it is undefined when attempting to assign a response cookie in Express framework

Today's operation that I've carried out countless times seems to be going awry. For some reason, I am unable to set a refresh token cookie using Express. Here is the error message in full /home/me/Code/apGymBE/node_modules/express/lib/response.j ...

Trouble with Displaying Events on React Big Calendar with Typescript

Struggling to implement React Big Calendar with TypeScript. Managed to get the calendar to display correctly after adjusting the height, but unable to show any events. The array of events is populating as expected, and I modified the code for TypeScript co ...

Converting JSON into a flattened structure by extracting only the final object

I am working with a JSON data structure that appears as follows, { "users": [ { "displayName": "Sharad Dutta", "givenName": "", "surname": "", "extens ...

The error message "Property 'matches' does not exist on type 'EventTarget'." is displayed on the output of angular-cli

Despite no errors showing up in the Chrome console, the code is functioning properly. constructor() { window.onclick = (event: MouseEvent) => { if (!event.target.matches('.dropbtn')) { const dropdowns = document.getElements ...

What is the best way to incorporate audio playback while browsing files on an HTML5 webpage with TypeScript?

<input type="file" id="soundUrl" (change)="onAudioPlay()" /> <audio id="sound" controls></audio> This is the HTML code I'm working with, and I'm looking to trigger audio playback after a user selects an MP3 file using TypeScrip ...

Is it possible to safely remove a class instance containing a GLcontext within a react.FC State to prevent memory leaks, especially when using a "class object with THREE.js"?

I have successfully developed a react.FC() application. In this application, you have the ability to throw a bottle in the metaverse (like a message in a bottle) to be discovered in the future. The app retrieves information from an API and constructs a c ...

String defines the type

I came across the following code snippet in some external sources that I intend to incorporate into my project: const INIT: 'jsonforms/INIT' = 'jsonforms/INIT' Can someone explain what it means to define a type with a string like INIT ...

Is there a way to break out of a while loop that is based on user input?

I am managing a basic system with server and client terminals. The server is responsible for receiving strings from the client and processing them. In order to trigger the server's processing, it must receive the designated end_of_input character, whi ...

How to determine the size of a char** string array?

Is there a way to find the length of an array stored as char** instead of char* []? char* arr[] = {"some", "thing"}; To get the length of the above string array, you can simply use the following code: size_t length = sizeof(arr)/sizeof(char*); This wil ...

How to handle a Node.js promise that times out if execution is not finished within a specified timeframe

return await new Promise(function (resolve, reject) { //some work goes here resolve(true) }); Using Delayed Timeout return await new Promise(function (resolve, reject) { //some work goes here setTimeout(function() { resolve(true); }, 5000); } ...

The validation process in reactive forms is experiencing some issues with efficiency

Trying to debug an issue with my reactive forms - the repeatPassword field doesn't update as expected. When entering information in the "password" field, then the "repeatPassword" field, and back to "password", the second entry is not flagged as inval ...

Displaying the same field multiple times within a form (organized into a list), with all entries being stored in an array upon submission - utilizing mongodb, express, ejs, and node js

I am facing a challenge in resolving this issue. I am relatively new to coding and have not been able to find a solution online. My goal is to convert these fields into an array. I have created multiple inputs like PIC#2, etc. I am connecting this model ...

Tips for retrieving empty fields from a database

I'm trying to extract empty fields from a database, but the code I've written doesn't seem to be working. function find_empty_fields($user_last_ad_id){ $query = $this->db->query( "SELECT * FROM ad WHERE ad_user_id = ? ...