打字稿:向上或向下扩展一个reciepe对象?

时间:2017-01-08 14:55:33

标签: javascript angular typescript

我的应用程序中有一些reciepes,想要将它们放大或缩小到卡路里量。

我的reciepe对象如下所示:

{
  title: "some title",
  calories: 700,
  fat: 20,
  carbs: 10,
  protein: 40,
  //...
  ingredient: [
    {
      name: "sugar",
      amount: 20,
      measurement: "g"
    },
    {
      name: "banana",
      amount: 1,
      measurement: "piece"
    }
  ]
}

我的问题:什么是最好的方法来扩展到1000卡路里或将其缩小到例如400卡路里?

是否可以使用整个对象进行经典的“3组”:首先计算100卡路里的这个重量,然后用所有属性计算400,500或1000卡路里?

感谢您的帮助:)

2 个答案:

答案 0 :(得分:1)

说你的食谱是这样的:

const recipe = {
  title: "some title",
  calories: 700,
  fat: 20,
  carbs: 10,
  protein: 40,
  //...
  ingredient: [
    {
      name: "sugar",
      amount: 20,
      measurement: "g"
    },
    {
      name: "banana",
      amount: 1,
      measurement: "piece"
    }
  ]
}

第一步:找出比例因子:

const desiredCalorieCount = 1000;
const scalingFactor = desiredCalorieCount / recipe.calories

第二步:创建一个函数,将每个数字乘以缩放系数。

function transformObjectByScalingFactor(obj: any) {
    for (const key in obj) {
        if (typeof recipe[key] !== "number") { continue; }

        recipe[key] *= scalingFactor;
    } 
}

第三步:大量调用此功能。

transformObjectByScalingFactor(recipe);
recipe.ingredient.map(x => transformObjectByScalingFactor(x))

可选步骤4:使函数递归,因此您只需调用一次。

答案 1 :(得分:1)

这似乎有效:

interface Ingredient {
    name: string;
    amount: number;
    measurement: "g" | "piece";
}

interface Reciepe {
    title: string;
    calories: number;
    fat: number;
    carbs: number;
    protein: number;
    ingredient: Ingredient[];
}

function scale(reciepe: Reciepe, calories: number): Reciepe {
    const ratio = calories / reciepe.calories;
    const scaled = Object.assign({}, reciepe);

    scaled.calories = calories;
    scaled.fat = reciepe.fat * ratio;
    scaled.carbs = reciepe.carbs * ratio;
    scaled.protein = reciepe.protein * ratio;

    for (let i = 0; i < reciepe.ingredient.length; i++) {
        scaled.ingredient[i].amount = reciepe.ingredient[i].amount * ratio;
    }

    return scaled;
}

code in playground