DEV Community

Cover image for Iterator design pattern O'zbek tilida
Ismoil Turdaliyev
Ismoil Turdaliyev

Posted on

Iterator design pattern O'zbek tilida

Iterator design pattern

🎯

Iterator design pattern - bu kollektsiyadagi obyektlar (masalan, massivlar, ro'yxatlar, daraxtlar) ustida birma-bir yurish (iteratsiya qilish) uchun ishlatiladi. Bu pattern yordamida kollektsiyaning ichki tuzilishini bilmasdan, uning elementlariga kirish mumkin.

Masalan, sizda katta kitoblar ro'yxati bor va har bir kitobni birma-bir ko'rib chiqmoqchisiz. Iterator pattern sizga shu jarayonni osonlashtiradi!
Qismlar:
Iterable interfeysi: Kollektsiya ichida yurish uchun iteratorni qaytaradi.
Iterator interfeysi: Kollektsiya ustida yurish uchun next(), hasNext() kabi metodlarni ta'minlaydi.
Konkret kollektsiya: Bu kollektsiya yoki to'plam bo'lib, unda iteratorni yaratish lozim.
Konkret iterator: Kollektsiya elementlarida yurishni ta'minlaydi.

// 1. Iteratorni yaratadigan funksiya
function createIterator<T>(items: T[]) {
  let index = 0; // Iterator ichki holati (closure ichida yashiringan)

  return {
    next: (): T | null => {
      if (index < items.length) {
        return items[index++];
      }
      return null;
    },
    hasNext: (): boolean => index < items.length,
  };
}

// 2. Foydalanish
const books = [
  { title: "O'tgan kunlar" },
  { title: "Mehrobdan Chayon" },
  { title: "Ikki eshik orasi" },
];

const bookIterator = createIterator(books);

while (bookIterator.hasNext()) {
  const book = bookIterator.next();
  console.log(book?.title);
}
Enter fullscreen mode Exit fullscreen mode

Javob:

O'tgan kunlar
Mehrobdan Chayon
Ikki eshik orasi

Yanam yaxshiroq:

// 1. Filtrlash imkoniyatiga ega iteratorni yaratadigan funksiya
function createFilteredIterator<T>(items: T[], filterFn: (item: T) => boolean) {
  let index = 0;

  return {
    next: (): T | null => {
      while (index < items.length) {
        const item = items[index++];
        if (filterFn(item)) {
          return item;
        }
      }
      return null;
    },
    hasNext: (): boolean => {
      for (let i = index; i < items.length; i++) {
        if (filterFn(items[i])) {
          return true;
        }
      }
      return false;
    },
  };
}

// 2. Foydalanish
const users = [
  { name: "Ali", isActive: true },
  { name: "Vali", isActive: false },
  { name: "Salim", isActive: true },
  { name: "Dilnoza", isActive: false },
];

// Aktiv foydalanuvchilarni iteratsiya qilish uchun iterator yaratamiz
const activeUserIterator = createFilteredIterator(users, (user) => user.isActive);

while (activeUserIterator.hasNext()) {
  const user = activeUserIterator.next();
  console.log(user?.name);
}
Enter fullscreen mode Exit fullscreen mode

Javobi:
Ali
Salim

🎞 https://youtu.be/PAmrBOrXLAE

DESIGN_PATTERN #ITERATOR

Top comments (0)