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

جواب «Square and Rectangle» چالش 3 از جلسه‌ی 19

سؤال

دو خط آخر برنامه آماده است، ولی نوع‌ها و تابع هنوز نوشته نشده‌اند. بالای آن‌ها بنویس:
۱. interface Square با kind: "square" و side: number
۲. interface Rect با kind: "rect" و width و height از نوع number
۳. type Shape = Square | Rect;
۴. تابع area(s: Shape): number با switch روی s.kind: مربع side * side و مستطیل width * height.

برنامه باید 16 و 12 را نشان بدهد.

راهنما

داخل تابع: switch (s.kind) { case "square": return s.side * s.side; case "rect": return s.width * s.height; }

یک جواب درست

<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 Square {
  kind: "square";
  side: number;
}

interface Rect {
  kind: "rect";
  width: number;
  height: number;
}

type Shape = Square | Rect;

function area(s: Shape): number {
  switch (s.kind) {
    case "square":
      return s.side * s.side;
    case "rect":
      return s.width * s.height;
  }
}

show(area({ kind: "square", side: 4 }));
show(area({ kind: "rect", width: 3, height: 4 }));
</script>

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