おいしいペストパスタのための(不変)変更可能な買い物リスト

王林
リリース: 2024-08-21 09:01:02
オリジナル
398 人が閲覧しました

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

ペストパスタはG-dが存在する証拠です

人生の中で、自家製カッペリーニ (エンジェルヘア) に山盛りの新鮮なペストを添える以上に嬉しいことはほとんどありません。私は真のグルメで、特にイタリア料理に関しては、いつもより複雑なレシピに挑戦していますが、このようなミニマルな料理のシンプルさと楽しさは満足をやめることがありません。もし最後の食事を選ぶという(不運な)幸運があったとしたら、パスタよりも寿司かペストかという難しい決断になるだろうが、それでも最終的にはペストパスタが勝つと思う。

ペストの話をするとお腹が空いてくる

どうすればいいですか?さて、もちろんペストパスタを作ります。時には「Quando a Roma!」と言いたくなることもあります。

まずは、フレンドリーなイタリアのマーケット「Il Mercato di Giovanni」で買う食材のリストを作成しましょう。不変オブジェクト配列と可変オブジェクト配列の両方を使用して、2 つのレシピから買い物リストを作成します。必要なことを単に書き出す方が効率的ですが、そのほうがはるかに楽しいのはご存知でしょう。ペストパスタの作り方をプログラムする方法について、あなたは飢えていると思います。それでは、早速詳しく見ていきましょう。「マンジャ マンジャ!」

個別のパスタとペストのレシピ配列を作成する

まず、pastaRecipeArray と pestoRecipeArray の変数を宣言します。各変数はオブジェクトの配列に割り当てられ、各オブジェクトは個々の材料を表します。

配列値を各変数に割り当てるときは、Object.freeze() メソッドを使用して、配列値が不変であることを確認します。 (これについては後で詳しく説明します)

各レシピ オブジェクトには、次のようなキーと値のペアを持つ 3 つのプロパティがあります。

  • 'name' = '文字列' の形式の材料の名前
  • 'recipe' = 材料がどのレシピに必要か (パスタ、ペスト、または両方) を示す、'配列' 形式の値
  • 'price' = かなり非現実的なダミー コンテンツを使用した、「数値」形式の米ドルでの材料の価格

(注: この投稿では内容を簡潔かつ比較的シンプルにするために、数量やその他の詳細を省略しました。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)
})
ログイン後にコピー

コンソールでリストが 1 つに結合されていることがわかります。今回は各成分名のみが記録されています。

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!