Fargho Fargho - 3 months ago 15
TypeScript Question

Typescript: get random entries from object with conditions and add them to a new object

I'm currently playing around with

Ionic2
and
Typescript
a little bit.

I have an object with some meals, a calorie count and a meal type (vegan and so on).

This object looks like this:

[
{
"id":14093,
"name":"Proteinshake mit Wasser – ESN Designer Whey Protein",
"description":"",
"thumbnail":null,
"image":null,
"calories":[
"200"
],
"type":[
"snack"
],
"nutrition":[
"pescetarier",
"standart",
"vegetarisch"
]
},
{
"id":14088,
"name":"Omelette mit Garnelen",
"description":"",
"thumbnail":null,
"image":null,
"calories":[
"400"
],
"type":[
"fruehstueck",
"gericht"
],
"nutrition":[
"pescetarier",
"standart",
"vegetarisch"
]
}
]


Now i want to generate a random meal plan.

I want to add 3 random meals with 400 calories and 2 Snacks with 200 calories.

Is it somehow possible to "select" the meals randomly by the calorie value?

Answer

Of course it's possible. Please take a look at this plunker. It's just a small demo but you can use it to obtain as many meals as you want.

The code is pretty much self-explanatory:

import { Component } from "@angular/core";

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  // Your array of meals
  private mealLists: Array<any> = [{...}, {...}, ...]; 

  // The array that's going to store the random meals
  private mealsPlan: Array<any> = [];

  constructor() { }

  // Creates a plan with *mealCount* meals with *calories* calories 
  public getMealPlan(mealCount: number, calories: number) {

    // Reset the data
    this.mealsPlan = [];

    for(let i=0; i<mealCount; i++) {
      // Get all the meals with 200 calories
      let selectedMeals = this.getMealsWithCertainCalories(calories);

      // Get a random meal from that list of meals
      let randomMeal = this.getRandomMeal(selectedMeals);

      // Add that meal to the plan
      this.mealsPlan.push(randomMeal);
    }
  }

  // Select all the meals with *calories* calories
  private getMealsWithCertainCalories(calories: number) {
    return this.mealLists
      .filter(function(aMeal){
        if(parseInt(aMeal.calories[0]) == calories) {
          return true;
        } else {
          return false;
        }
      });
  }

  // Get random index between 0 and the amount of meal sent as parameter
  private getRandomMeal(selectedMeals) {
    let randomIndex = Math.floor((Math.random() * selectedMeals.length) );
    return selectedMeals[randomIndex];
  }

}

Please notice that all the magic is being done with the filter(...) and the Math.random() methods.