diff --git a/AgregatorImpl.ts b/AgregatorImpl.ts new file mode 100644 index 0000000..0a682ac --- /dev/null +++ b/AgregatorImpl.ts @@ -0,0 +1,19 @@ + +import { IAgregator } from "./IAgregator"; +import { IIterator } from "./IIterator"; +import { IteratorImpl } from "./IteratorImpl"; + +//Реализуем наш "агрегатор" +export class AgregatorImpl implements IAgregator { + private items: any[] = []; + + public createIterator(): IIterator { // Вызываем итератор + return new IteratorImpl(this); + } + public addItem(item: any): void { // Добавляем элементы в коллекцию + this.items.push(item); + } + public getItem(): any[] { // Получаем элементы коллекции + return this.items; + } +} \ No newline at end of file diff --git a/IAgregator.ts b/IAgregator.ts new file mode 100644 index 0000000..489d605 --- /dev/null +++ b/IAgregator.ts @@ -0,0 +1,7 @@ +import { IIterator } from "./IIterator"; + +export interface IAgregator { // Собираем в интерфейс методы для создания коллекции + createIterator(): IIterator // Создать итератор + addItem(item): void; // Добавить элемент + getItem(item): void // Получить элемент +} \ No newline at end of file diff --git a/IIterator.ts b/IIterator.ts new file mode 100644 index 0000000..e3a8a82 --- /dev/null +++ b/IIterator.ts @@ -0,0 +1,4 @@ +export interface IIterator { // Определяет общий интерфейс для доступа и обхода элементов. + next(): T; // получить следующий элемент + hasNext(): boolean; // есть ли следующий элемент +} \ No newline at end of file diff --git a/IteratorImpl.ts b/IteratorImpl.ts new file mode 100644 index 0000000..6baf890 --- /dev/null +++ b/IteratorImpl.ts @@ -0,0 +1,17 @@ +import { IIterator } from "./IIterator"; +import { IAgregator } from "./IAgregator"; + +// Реализуем итератор +export class IteratorImpl implements IIterator { + private collection: IAgregator; + private key: number = 0; + constructor(collection: IAgregator) { // создаем коллекцию + this.collection = collection; + } + public next(): any { // Возвращаем следующий элемент + return this.collection.getItem(this.key++); + } + public hasNext(): boolean { // Проверяем наличие следующего элемента + return this.collection.getItem(this.key++) ? true : false; + } +} \ No newline at end of file diff --git a/main.ts b/main.ts new file mode 100644 index 0000000..c3e1b8c --- /dev/null +++ b/main.ts @@ -0,0 +1,14 @@ +import { AgregatorImpl } from "./AgregatorImpl"; + +const collection = new AgregatorImpl(); +//Добавляем в коллекцию +collection.addItem(false); // bool +collection.addItem('Sun'); // string +collection.addItem([4, 3, 5]); // array +collection.addItem(10); // number + +const iterator = collection.createIterator(); // Создаем итератор + +while (iterator.hasNext()) { // Пока есть следующий элемент печатаем его + console.log(iterator.next()); +} \ No newline at end of file