Step 4: Stop, Go, Wait چالش 4 از جلسهی 20، سخت
قدم آخر: چراغ به راننده هم بگوید چه کند.
- نوع Action را بساز که فقط "stop"، "go" یا "wait" باشد.
- تابع action(now: Light): Action را با switch و never بنویس: قرمز "stop"، سبز "go" و زرد "wait".
- draw را عوض کن تا کار راننده را هم داخل پرانتز بنویسد.
اول باید Light: red (stop) دیده شود. با زدن دکمه: Light: green (go)، Light: yellow (wait) و دوباره Light: red (stop).
<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>
<button id="go" onclick="press()">Next</button>
<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";
// 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;
}
}
}
// 3. the button
function draw(): void {
show("Light: " + light);
}
function press(): void {
light = next(light);
draw();
}
draw();
// 4. what the driver does
</script>
راهنما و جواب این چالش · برگشت به درس جلسهی 20: پروژه: چراغ راهنماییای که اشتباه نمیکند
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js