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

جواب «Cat or Dog» چالش 2 از جلسه‌ی 19

سؤال

تابع about درباره‌ی یک حیوان خانگی می‌نویسد. ولی pet شاید سگ باشد، و سگ lives ندارد. برای همین خط قرمز می‌گیرد.
اول برچسب را بپرس: اگر pet.kind برابر "cat" بود همان جمله‌ی گربه، وگرنه dog with و تعداد tricks و tricks.
برنامه باید cat with 9 lives و dog with 3 tricks را نشان بدهد.

راهنما

if (pet.kind === "cat") { return "cat with " + pet.lives + " lives"; } و بعد از آن return "dog with " + pet.tricks + " tricks";

یک جواب درست

<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 Cat {
  kind: "cat";
  lives: number;
}

interface Dog {
  kind: "dog";
  tricks: number;
}

type Pet = Cat | Dog;

function about(pet: Pet): string {
  if (pet.kind === "cat") {
    return "cat with " + pet.lives + " lives";
  }
  return "dog with " + pet.tricks + " tricks";
}

show(about({ kind: "cat", lives: 9 }));
show(about({ kind: "dog", tricks: 3 }));
</script>

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