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

جواب «Find the Red Lines» چالش 5 از جلسه‌ی 28

سؤال

این برنامه یک دسته بشقاب است. باید RED و بعد 1 را نشان بدهد. سه اشتباه دارد، و یکی از آن‌ها تا بقیه را درست نکنی دیده نمی‌شود.
- pop می‌گوید همیشه یک T می‌دهد. ولی اگر پشته خالی باشد چه؟ نوع جوابش را درست کن.
- پشته‌ی plates برای متن است. بشقاب دوم باید "red" باشد، نه 7.
- حالا plate شاید undefined باشد. قبل از plate.toUpperCase() با یک if مطمئن شو.

راهنما

۱) pop(): T | undefined { ۲) plates.push("red"); ۳) if (plate !== undefined) { show(plate.toUpperCase()); }

یک جواب درست

<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 Stack<T> {
  private items: T[] = [];

  push(item: T): void {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }

  get size(): number {
    return this.items.length;
  }
}

const plates = new Stack<string>();
plates.push("blue");
plates.push("red");

const plate = plates.pop();
if (plate !== undefined) {
  show(plate.toUpperCase());
}
show(plates.size);
</script>

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