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

جواب «The Rectangle» چالش 6 از جلسه‌ی 21

سؤال

یک کلاس از صفر بنویس: Rectangle (مستطیل).
۱. دو فیلد با نوع number: width و height. سازنده هر دو را به همین ترتیب می‌گیرد.
۲. متد area(): number که مساحت را برمی‌گرداند (width * height).
۳. متد grow(n: number): void که n را به هر دو فیلد اضافه می‌کند.
بعد این برنامه را زیرش بنویس:
- const r = new Rectangle(3, 4); و مساحت را نشان بده (12).
- r.grow(1); و بعد show(r.width, r.height); (4 5).
- دوباره مساحت را نشان بده (20).

راهنما

در سازنده: this.width = width; و this.height = height;. در area: return this.width * this.height;. در grow هر دو فیلد را n تا زیاد کن.

یک جواب درست

<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">
class Rectangle {
  width: number;
  height: number;

  constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
  }

  area(): number {
    return this.width * this.height;
  }

  grow(n: number): void {
    this.width = this.width + n;
    this.height = this.height + n;
  }
}

const r = new Rectangle(3, 4);
show(r.area());
r.grow(1);
show(r.width, r.height);
show(r.area());
</script>

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