بتل کد Battle Codeدارد باز می‌شود…

جواب «Step 3: Total and Cheapest» چالش 3 از جلسه‌ی 15

سؤال

قدم سوم: دو تابع برای قفسه. زیر کد قبلی بنویس:
- تابع total یک Item[] می‌گیرد و جمع قیمت‌ها را (یک number) برمی‌گرداند.
- تابع cheapest یک Item[] می‌گیرد و ارزان‌ترین کالا را (یک Item) برمی‌گرداند.
- بعد از سه خط قبلی، دو خط دیگر نشان بده: Total: 85 و Cheapest: Potion.

راهنما

cheapest مثل «بهترین بازیکن» است: let best: Item = list[0]; و در حلقه if (item.price < best.price) { best = item; }. برای نشان دادن: show("Total: " + total(items)); و show("Cheapest: " + cheapest(items).name);

یک جواب درست

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Item {
  name: string;
  price: number;
}

function label(item: Item): string {
  return item.name + ": " + item.price + " coins";
}

const items: Item[] = [
  { name: "Sword", price: 30 },
  { name: "Shield", price: 45 },
  { name: "Potion", price: 10 },
];

for (const item of items) {
  show(label(item));
}

function total(list: Item[]): number {
  let sum: number = 0;
  for (const item of list) {
    sum = sum + item.price;
  }
  return sum;
}

function cheapest(list: Item[]): Item {
  let best: Item = list[0];
  for (const item of list) {
    if (item.price < best.price) {
      best = item;
    }
  }
  return best;
}

show("Total: " + total(items));
show("Cheapest: " + cheapest(items).name);
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن