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

جواب «Step 2: What Comes Next» چالش 2 از جلسه‌ی 20

سؤال

قدم دوم: بعد از هر رنگ چه می‌آید؟
- تابع next(now: Light): Light را با switch بنویس: بعد از "red" رنگ "green"، بعد از "green" رنگ "yellow" و بعد از "yellow" دوباره "red".
- یک default با const forgot: never = now; بگذار تا هیچ رنگی جا نیفتد.
- برای امتحان، زیر خط اول این سه را هم نشان بده: next("red")، next("green") و next("yellow").

برنامه باید چهار خط نشان بدهد: Light: red، green، yellow و red.

راهنما

داخل switch (now): case "red": return "green"; و همین‌طور برای دو رنگ دیگر. بعد از تابع: show(next("red"));

یک جواب درست

<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">
// 1. the type Light and the box light
type Light = "red" | "green" | "yellow";
let light: Light = "red";
show("Light: " + light);

// 2. the function next
function next(now: Light): Light {
  switch (now) {
    case "red":
      return "green";
    case "green":
      return "yellow";
    case "yellow":
      return "red";
    default: {
      const forgot: never = now;
      return forgot;
    }
  }
}

show(next("red"));
show(next("green"));
show(next("yellow"));
</script>

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