首页  >  文章  >  web前端  >  一份(不)可变的美味香蒜意大利面购物清单

一份(不)可变的美味香蒜意大利面购物清单

王林
王林原创
2024-08-21 09:01:02419浏览

An (Im)mutable Shopping List for a Delicious Pesto Pasta

香蒜酱意大利面证明上帝存在

生活中没有什么比在自制的卡佩里尼(天使发)上享用大量新鲜香蒜酱更让我高兴的了。我是一个真正的美食家 - 尤其是在意大利美食方面 - 并且总是尝试更复杂的食谱,但这种极简主义菜肴的简单性和享受永远不会停止满足。如果我有幸选择最后一顿饭,那么在寿司和香蒜酱和意大利面之间做出艰难的决定将是一个艰难的决定,但我仍然认为香蒜意大利面最终胜出。

所有关于香蒜酱的讨论让我很饿

我该怎么办?好吧,当然是做香蒜意大利面。有时你只需说:“Quando a Roma!”

让我们首先列出从我们友好的意大利市场“Il Mercato di Giovanni”购买的食材清单。我们将使用不可变和可变对象数组从两个食谱创建购物清单。虽然简单地写出我们需要的东西会更有效,但你知道这更有趣。我可以告诉你渴望了解更多关于如何编程制作香蒜酱意大利面的信息,所以让我们挖掘。“Mangia Mangia!”

创建单独的意大利面和香蒜酱食谱数组

我们首先声明 PastaRecipeArray 和 pestoRecipeArray 的变量,每个变量分配给一个对象数组,其中每个对象代表一种单独的成分。

当我们为每个变量分配数组值时,我们使用 Object.freeze() 方法来确保它们是不可变的。 (稍后详细介绍)

每个菜谱对象都有三个属性,键值对如下:

  • '名称' = “字符串”形式的成分名称
  • 'recipe' = 一个或多个值,以“数组”的形式表示,指示哪种配方需要该成分(意大利面、香蒜酱或两者)
  • '价格' = 成分的美元价格,以“数字”的形式,使用相当不切实际的虚拟内容

(注意:我在这篇文章中省略了数量和其他细节,以使事情简短且相对简单。我们也可以使用 JSON 来实现这些对象,但我们让事情易于消化 此处。)

建立这些数组的代码将如下所示:

const pastaRecipeArray = Object.freeze([
  { "name": "Eggs", "recipe": ["pasta"], "price": 6.99 },
  { "name": "Extra Virgin Olive Oil", "recipe": ["pasta", "pesto"], "price": 12.59 },
  { "name": "Kosher Salt", "recipe": ["pasta", "pesto"], "price": 7.89 },
  { "name": "Semolina Flour", "recipe": ["pasta"], "price": 12.95 }
])

const pestoRecipeArray = Object.freeze([
  { "name": "Basil", "recipe": ["pesto"], "price": 6.99 },
  { "name": "Black Pepper", "recipe": ["pesto"], "price": 9.99 },
  { "name": "Extra Virgin Olive Oil", "recipe": ["pasta", "pesto"], "price": 12.59 },
  { "name": "Kosher Salt", "recipe": ["pasta", "pesto"], "price": 7.89 },
  { "name": "Parmesan", "recipe": ["pesto"], "price": 15.99 },
  { "name": "Pine Nuts", "recipe": ["pesto"], "price": 13.98 }
])

您会再次注意到配方键指向一个数组形式的值。我们这样设置是因为两个食谱中都使用了一些成分。

为了测试 PastaRecipeArray 是否正确设置,我们可以利用 .forEach() 方法,这是一个用于迭代数组中每个对象的回调函数。使用成分作为参数,我们可以将其登录到控制台,如下所示:

pastaRecipeArray.forEach((ingredient) => {
  console.log(ingredient)
})

当您检查控制台时,您应该看到类似以下输出的内容:

Object {name: "Eggs", recipe: Array(1), price: 6.99}
Object {name: "Extra Virgin Olive Oil", recipe: Array(2), price: 12.59}
Object {name: "Kosher Salt", recipe: Array(2), price: 7.89}
Object {name: "Semolina Flour", recipe: Array(1), price: 12.95}

类似地,我们可以像这样记录我们的pestoRecipeArray:

pestoRecipeArray.forEach((ingredient) => {
  console.log(ingredient)
})

结果如下:

Object {name: "Basil", recipe: Array(1), price: 6.99}
Object {name: "Black Pepper", recipe: Array(1), price: 9.99}
Object {name: "Extra Virgin Olive Oil", recipe: Array(2), price: 12.59}
Object {name: "Kosher Salt", recipe: Array(2), price: 7.89}
Object {name: "Parmesan", recipe: Array(1), price: 15.99}
Object {name: "Pine Nuts", recipe: Array(1), price: 13.98}

(注意:当您看到 Array(1) 和 Array(2) 等输出时,您可能想要重写函数来选择这些键,或者只需单击控制台中的数组即可查看详细信息它包含什么。)

创建购物清单数组

现在我们已经建立了食谱数组,我们想要继续下一步,创建一个购物清单数组。为此,我们需要将对象数组 PastaRecipeArray 和 pestoRecipeArray 组合到一个名为 shoppingListArray 的新可变变量中。我们将使用扩展运算符来做到这一点......就像这样:

const shoppingListArray = [...pastaRecipeArray, ...pestoRecipeArray]

现在让我们使用下面的 console.log() 来看看我们的新列表是什么样子的。展望未来,我们将记录对象内的属性值而不是整个对象,以消除一些混乱。您将需要使用此代码来查看我们的列表在流程的每个步骤之后如何变化。

shoppingListArray.forEach((ingredient) => {
      console.log(ingredient.name)
})

我们可以看到我们的列表已在控制台中合并为一个,这次仅记录每种成分名称。

Eggs
Extra Virgin Olive Oil
Kosher Salt
Semolina Flour
Basil
Black Pepper
Extra Virgin Olive Oil
Kosher Salt
Parmesan
Pine Nuts

不可变数组与可变数组

为什么我们应该让 PastaRecipeArray 和 pestoRecipeArray 不可变?使它们不可变使得我们在分配它们后无法更改它们的值。我们不想撕毁这些食谱。我们希望拯救他们,迎接另一个辉煌的一天。无论我们要在临时的、可变的购物清单上写什么,这些一成不变的家庭食谱都需要继续下去。

我们还希望能够从新创建的 shoppingListArray 中添加或删除成分,以使这道菜符合我们的特定口味,当然不会影响我们原来的食谱。

Adding, replacing, and deleting ingredients

As you may have noticed, when we combined our pasta and pesto recipes into our shopping list we ended up with duplicates for "Extra Virgin Olive Oil" and "Kosher Salt". We don't need to buy these twice so let's get rid of them. There are fancier ways to eliminate duplicates, but for now we will use .splice() to remove the first Extra Virgin Olive Oil object.

The .splice() method destructively deletes or replaces elements in an array. The first parameter represents the first element we are deleting and the second parameter represents how many elements we want to delete from that start point. While "Extra Virgin Olive Oil" is the second object in the array, arrays start at '0', so technically the second object is represented by a '1'. Let's execute the following:

shoppingListArray.splice(1, 1)

In the console you will see that there is now only one "Extra Virgin Olive Oil" object. (note: If you try to use .splice() or similar methods on one of our original recipe arrays you will get a TypeError because we used Object.freeze(), making them immutable.)

We still have an extra "Kosher Salt", and now we are going to use .splice() to it's full power. In addition to our first two parameters we have a third parameter that can replace elements in an array with new elements. I love to add a bit of lemon to my pesto, and I don't like food that is too salty, so let's go ahead and replace our extra "Kosher Salt" with our new "Lemon" object. We will declare our lemon object as a variable for better readibility and include it as the third .splice() parameter.

const lemon = { "name": "Lemon", "recipe": ["pesto"], "price": 2.04 }

shoppingListArray.splice(6, 1, lemon)

Today I'm feeling a bit saucy so let's change things up a bit and add in some roasted tomatoes using .push(). With .push() we can add elements to the end of the array, with each parameter representing a new element. So let's add some "Cherry Tomatoes" to our list. Come to think of it, I forgot the "Garlic" too!

const tomatoes = { "name": "Cherry Tomatoes", "recipe": ["pesto"], "price": 5.99 }

const garlic = { "name": "Garlic", "recipe": ["pesto"], "price": 2.99 }

shoppingListArray.push(tomatoes, garlic)

Organizing our shopping list

Now that we have all our ingredients well established let's organize them in a way that will make our shopping experience seamless.

Let's organize our list alphabetically using .sort().

shoppingListArray.sort((a, b) => {
  const nameA = a.name
  const nameB = b.name

  if (nameA < nameB) {
    return -1
  }
  if (nameA > nameB) {
    1
  }
  return 0
})

Our shopping list now looks like this in the console.

Basil
Black Pepper
Cherry Tomatoes
Eggs
Extra Virgin Olive Oil
Garlic
Kosher Salt
Lemon
Parmesan
Pine Nuts
Semolina Flour

Planning ahead for our expected costs

Now we are ready to go to the market, but first let's make sure we know how much money we need, using .reduce(). There is a lot to go over with .reduce(), and I'm getting hungry, so I'll skip over the details.

const ingredientsPrice = shoppingListArray.reduce((accumulator, ingredient) => {
  return accumulator + ingredient.price
}, 0)

console.log("You will need $" + ingredientsPrice + " to make pesto pasta. Man is life is expensive.")
// You will need $98.39 to make pesto pasta. Wow, life is expensive.

Creating new recipe list arrays

So we went to the store and got our ingredients, but now we want to separate our ingredients back into their respective recipes, just to lay everything out on the table and keep things in order. Lets create two new arrays, pastaIngredients and pestoIngredients using .filter(), .includes(), and of course .forEach() to log them to the console.

const pastaIngredients = shoppingListArray.filter((ingredient) => {
  return ingredient.recipe.includes('pasta')
})

pastaIngredients.forEach((ingredient) => {
  console.log(ingredient.name)
})
const pestoIngredients = shoppingListArray.filter((ingredient) => {
  return ingredient.recipe.includes('pesto')
})

pestoIngredients.forEach((ingredient) => {
  console.log(ingredient.name)
})

"Wrapping" it up

As you can see from logging these to the console we successfully created a shoppingListArray that didn't modify our original immutable recipe arrays, pastaRecipeArray and pestoRecipeArray. We then were able to mutably modify the shoppingListArray in a destructive manner to add, delete, and replace ingredients to our liking. We also calculated how much we needed to spend before going to the store. Lastly, we were able to separate these ingredients back into their respective recipes, pastaIngredients and pestoIngredients in preparation for a brilliant meal.

Well, what a delicious dish that was. I hope you enjoyed it as much as I did. Again, Mangia Mangia!

以上是一份(不)可变的美味香蒜意大利面购物清单的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn