Search code examples
javascriptarraysrandom

Reset randomization after it goes through all the items in the array


I'm learning JS and I just finished a project, here the code:

const menu = {
    _meal: "",
    _price: 0,
    //Let set the new value of meal only if it's a string.
    set meal(mealToCheck) {
        if (typeof mealToCheck === "string") {
            return this._meal = mealToCheck;
        }
    },
    //Let set the new value of price only if it's a number.
    set price(priceToCheck) {
        if (typeof priceToCheck === "number") {
            return this._price = priceToCheck;
        }
    },
    //If both setters are true, then return a message using them, otherwise return message saying the values are wrong.
    get todaysSpecial() {
        if (this._meal && this._price) {
            return `Today's Special is ${this._meal}, for just ${this._price}£!!`;
        } else {
            return "Meal and Price wasn't entered correctly!!";
        }
    }
};

//Arrays for the meal options and respective prices, also a constant to get a random number in the array range.
const meals = ["Pizza", "Steak", "Pie", "Roast", "Moussaka", "Lasagne", "Tacos"];
const prices = [/*Pizza*/9, /*Steak*/13, /*Pie*/11, /*Roast*/14, /*Moussaka*/9, /*Lasagne*/10, /*Tacos*/9];
const random = Math.floor(Math.random() * meals.length);

//Assigns a new random value from the arrays. I used a single randomizer so that you can combine a plate to its price by the index number.
menu.meal = meals[random];
menu.price = prices[random];

//Check if the number of items in the meals and prices array it's equal, and if it is, creates the menu of the day string.
if (meals.length === prices.length) {
    console.log(menu.todaysSpecial);
} else {
    console.log("The number of prices and meals don't match!!");
}

At the end of the code I added a couple of arrays and a Math.random so that every time I run it, it gives me a different value.

Now I'm trying to find a way to have the random value give unique values until it reaches the array length, and then restart. At the moment I have 7 items in the array simulating the day of the week, I'd like to have each item coming out once per week and then reset.

I know how to do it by following the array index order, but I can't come out with a way to do it randomly, any input?


Solution

  • You can combine your prices and meals array to make it a bit simpler, then shuffle it.

    const menu = {
      _meal: "",
      _price: 0,
      //Let set the new value of meal only if it's a string.
      set meal(mealToCheck) {
        if (typeof mealToCheck === "string") {
          return (this._meal = mealToCheck);
        }
      },
      //Let set the new value of price only if it's a number.
      set price(priceToCheck) {
        if (typeof priceToCheck === "number") {
          return (this._price = priceToCheck);
        }
      },
      //If both setters are true, then return a message using them, otherwise return message saying the values are wrong.
      get todaysSpecial() {
        if (this._meal && this._price) {
          return `Today's Special is ${this._meal}, for just ${this._price}£!!`;
        } else {
          return "Meal and Price wasn't entered correctly!!";
        }
      }
    };
    
    //Arrays for the meal options and respective prices, also a constant to get a random number in the array range.
    let meals = [
      { name: "Pizza", price: 9 },
      { name: "Steak", price: 13 },
      { name: "Pie", price: 11 },
      { name: "Roast", price: 14 },
      { name: "Moussaka", price: 9 },
      { name: "Lasagne", price: 10 },
      { name: "Tacos", price: 9 }
    ];
    
    // Used to shuffle your meals array
    function shuffle(array) {
      let currentIndex = array.length,
        randomIndex;
    
      // While there remain elements to shuffle.
      while (currentIndex != 0) {
        // Pick a remaining element.
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex--;
    
        // And swap it with the current element.
        [array[currentIndex], array[randomIndex]] = [
          array[randomIndex],
          array[currentIndex]
        ];
      }
    
      return array;
    }
    
    meals = shuffle(meals);
    
    // Iterate meals
    for (let i = 0; i < meals.length; i++) {
      menu.meal = meals[i].name;
      menu.price = meals[i].price;
      console.log(menu.todaysSpecial);
    }