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

جواب «Find the Red Lines» چالش 5 از جلسه‌ی 27

سؤال

این برنامه باید Ali و بعد 40 را نشان بدهد. سه اشتباه دارد. شاید همه را با هم نبینی: یکی را که درست کنی، بعدی پیدا می‌شود.
- findById از item.id استفاده می‌کند، ولی T شرطی ندارد.
- findById شاید چیزی پیدا نکند. قبل از خواندن found.name با یک if مطمئن شو که undefined نیست.
- Player فیلدی به اسم points ندارد. اسم درست را بگذار.

راهنما

۱) function findById<T extends { id: number }>(...) ۲) if (found !== undefined) { show(found.name); } ۳) const key: keyof Player = "score";

یک جواب درست

<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 Player {
  id: number;
  name: string;
  score: number;
}

function findById<T extends { id: number }>(list: T[], id: number): T | undefined {
  for (const item of list) {
    if (item.id === id) {
      return item;
    }
  }
  return undefined;
}

const players: Player[] = [
  { id: 1, name: "Sara", score: 40 },
  { id: 2, name: "Ali", score: 25 },
];

const found = findById(players, 2);
if (found !== undefined) {
  show(found.name);
}

const key: keyof Player = "score";
show(players[0][key]);
</script>

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