I could use some assistance enhancing a function that populates an array with 4 random, non-repeating recipe objects based on their IDs. However, I now need to incorporate an additional requirement where the recipes must include one breakfast, one lunch, one snack, and one dinner item. For instance:
Here is an example of JSON containing recipes:
[
{
recipeId: 1,
recipeTypeId: 1, // Breakfast
"description": "someRecipe",
"img": "someImgBase64",
},
{
recipeId: 2,
recipeTypeId: 2, // Lunch
"description": "someRecipe",
"img": "someImgBase64",
},
{
recipeId: 3,
recipeTypeId: 3, // Snack
"description": "someRecipe",
"img": "someImgBase64",
},
{
recipeId: 4,
recipeTypeId: 4, // Dinner
"description": "someRecipe",
"img": "someImgBase64",
},
{
recipeId: 5,
recipeTypeId: 1, // Breakfast
"description": "someRecipe",
"img": "someImgBase64",
}
]
This is my current function:
randomRecipes() {
// Retrieve previously saved recipes from API
localStorage.getItem('recipesList');
// Random number generator
const randomIndex = new Set();
const recommendedRandomRecipes: [] = [];
while (randomIndex.size < 4) {
randomIndex.add(Math.floor(Math.random() * recipes.length));
}
randomIndex.forEach(i => recommendedRandomRecipes.push(recipes[Number(i)]));
localStorage.addItem('recommendedRecipes', recommendedRandomRecipes);
this.recipes = recommendedRandomRecipes;
}
The desired outcome:
recommendedRandomRecipes [1,2,3,4] or [2,3,4,5]
What I want to avoid:
RecommendedRandomRecipes [1,2,3,5] // Multiple breakfast items in the array