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

Step 3: Change One چالش 3 از جلسه‌ی 30، متوسط

قدم سوم: به کلاس یک متد update اضافه کن.
- update(id: number, changes: Partial<T>): boolean: چیز را با this.get(id) پیدا کن. اگر نبود، false برگردان. اگر بود، با Object.assign(item, changes); تغییرها را روی آن بریز و true برگردان.
بعد زیر کد این‌ها را بنویس:
- books.update(2, { price: 70 });
- کتاب ۲ را دوباره با get بگیر و اگر بود، عنوان و قیمتش را نشان بده: show(holes.title, holes.price);
- show(books.update(9, { price: 1 }));
دو خط تازه باید Holes 70 و false باشند (روی هم پنج خط).

<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 Book {
  id: number;
  title: string;
  price: number;
}

class Store<T extends { id: number }> {
  private items: T[] = [];

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

  all(): T[] {
    return this.items;
  }

  get(id: number): T | undefined {
    for (const item of this.items) {
      if (item.id === id) {
        return item;
      }
    }
    return undefined;
  }
}

const books = new Store<Book>();
books.add({ id: 1, title: "Matilda", price: 80 });
books.add({ id: 2, title: "Holes", price: 95 });
show(books.all().length);

const found = books.get(2);
if (found !== undefined) {
  show(found.title);
}
const missing = books.get(9);
if (missing === undefined) {
  show("not found");
}
</script>

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 30: پروژه: انبارِ همه‌چیز · چالش بعدی: Step 4: A Second Store

بیشتر بخوان: جاوااسکریپت چیست؟ از دکمه‌ی وب تا Node.js