skip to Main Content

The code below is supposed to generate 5 random indexes from an array, but I’m getting an infinite loop based on what I see in my console and it crashes the browser everytime. From my long hours of debugging, I realized it’s the matches.length line in the while loop that’s causing it. Any help on how to fix it will be much appreciated. Thank you.

const API_URL = 'http://127.0.0.1:8000/api/matches/';

  /*
  This is an async function that fetches matches from an API, generates a random selection of 5 matches,
  sets the selection to state, and updates the UI accordingly, while handling any errors that may occur.
   */
  async function generateRandomMatches() {
    try {
      const response = await axios.get(API_URL);
      const matches = await response.data;
      const newMatches: number[] = [];

      // The code generates a list of 5 unique random indexes between 0 and the length of matches array.
      while (newMatches.length < 5) {
        const randomIndex: number = Math.floor(Math.random() * matches.length);
        if (!newMatches.includes(randomIndex)) {
          newMatches.push(randomIndex);
        }
      }
      setSelectedMatches(newMatches);
      setShowMatches(true);
    } catch (error) {
      console.error(error);
    }
  }

2

Answers


  1. Chosen as BEST ANSWER

    I wrapped the entire while loop in an if-else condition. Like so

            # New code
           if (matches.length < 5) {
            console.log('There are less than 5 matches available.');
            return; 
           } else {
             # Old code is still here, nothing changed.
            while (newMatches.length < 5) {
              const randomIndex: number = Math.floor(
                Math.random() * matches.length
              );
              if (!newMatches.includes(randomIndex)) {
                newMatches.push(randomIndex);
              }
            }
          }
    

  2. You are going after matches.length then the while loop conditions is wrong.
    Think if matches containe 3 items then the while loop will never gets more then 3 and you are checking newMatches.length < 5.

    That is why the while loop never resolve.

    I added a fix by modifying the condition to newMatches.length != matches.length
    this should solve the issue.

    const create = () => {
      const newMatches= [];
      const matches = [1,0,2,5,6]
      while (newMatches.length != matches.length) {
        const randomIndex = Math.floor(Math.random() * matches.length);
        if (!newMatches.includes(randomIndex)) {
          newMatches.push(randomIndex);
        }
      }
      
      return newMatches
    }
    
    console.log(create())
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search