Home > database >  How to re-run a function if a condition within was not met
How to re-run a function if a condition within was not met

Time:08-18

In my redux slice, I imported an Array of objects, each object containing data of a certain country.

The function (in the reducer ) randomly selects two countries from the Array, I ran into a situation where Random1 and Random2 were the same, so I added a condition that Random1 should not be equal to Random2 before the function proceeds, in case if both of them were the same how I make the function re-run to generate two new random number till both are different from each other?

import { createSlice } from "@reduxjs/toolkit";
import { data } from "../data/countries";

const initialState = {
  countries: data,
  questionOption1: {
    image: "",
    title: "",
    area: 0,
  },
  questionOption2: {
    image: "",
    title: "",
    area: 0,
  },
  correctAnswer1: true,
  correctAnswer2: true,
  correctAnswer1Tick: 0,
  correctAnswer2Tick: 0,

  total: 0,
};

const countriesSlice = createSlice({
  name: "countries",
  initialState,
  reducers: {
    setQuestion1: (state) => {
      let Random1 =
        state.countries[Math.floor(Math.random() * state.countries.length)];
      let Random2 =
        state.countries[Math.floor(Math.random() * state.countries.length)];

      if (Random1 !== Random2) {
        state.questionOption1 = {
          image: Random1.image,
          title: Random1.title,
          area: Random1.area,
        };

        state.questionOption2 = {
          image: Random2.image,
          title: Random2.title,
          area: Random2.area,
        };
      }

      state.correctAnswer1 = true;
      state.correctAnswer2 = true;
      state.correctAnswer1Tick = 0;
      state.correctAnswer2Tick = 0;

      return state;
    },
});

export const countriesActions = countriesSlice.actions;
export default countriesSlice.reducer;

CodePudding user response:

You can just make sure random1 and random2 are not the same before moving on. You can do this using a while loop and resetting the value of random2 each loop until the two are no longer equal.

let Random1 =
  state.countries[Math.floor(Math.random() * state.countries.length)];
let Random2 =
  state.countries[Math.floor(Math.random() * state.countries.length)];

while (Random1 === Random2) {
  Random2 = state.countries[Math.floor(Math.random() * state.countries.length)];
}

// do other state stuff here. 

Another option is to randomly sort the countries array, then grabbing the first two.

const randomSort = state.countries.sort((a, b) => Math.random())

const random1 = randomSort[0];
const random2 = randomSort[1];

This assumes countries is an array of unique elements.

  • Related