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

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

سؤال

یک گروه موسیقی از صفر بنویس.
۱. interface Tunable با یک متد: tune(): string.
۲. کلاس abstract به اسم Instrument:
- فیلد static count از نوع number که از 0 شروع می‌شود.
- سازنده‌ی کوتاه با public readonly name: string که هر بار یکی به Instrument.count اضافه می‌کند.
- متد abstract sound(): string.
- متد play(): string که اسم، دونقطه، یک فاصله و صدا را برمی‌گرداند، مثل Drum: Boom.
۳. Drum فرزند Instrument که صدایش Boom است.
۴. Guitar فرزند Instrument که قول Tunable را هم می‌دهد. صدایش Twang است و tune متنی مثل Guitar is tuned برمی‌گرداند.
برنامه‌ی زیرش:
- const drum = new Drum("Drum"); و const guitar = new Guitar("Guitar");
- show(drum.play()); (Drum: Boom) و show(guitar.play()); (Guitar: Twang)
- show(guitar.tune()); (Guitar is tuned)
- show(Instrument.count); (2)

راهنما

class Guitar extends Instrument implements Tunable. در سازنده‌ی Instrument: Instrument.count = Instrument.count + 1;. در play: return this.name + ": " + this.sound();

یک جواب درست

<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 Tunable {
  tune(): string;
}

abstract class Instrument {
  static count: number = 0;

  constructor(public readonly name: string) {
    Instrument.count = Instrument.count + 1;
  }

  abstract sound(): string;

  play(): string {
    return this.name + ": " + this.sound();
  }
}

class Drum extends Instrument {
  sound(): string {
    return "Boom";
  }
}

class Guitar extends Instrument implements Tunable {
  sound(): string {
    return "Twang";
  }

  tune(): string {
    return this.name + " is tuned";
  }
}

const drum = new Drum("Drum");
const guitar = new Guitar("Guitar");
show(drum.play());
show(guitar.play());
show(guitar.tune());
show(Instrument.count);
</script>

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