Search This Blog

2023/08/31

Iterator Design pattern

 // Iterator Interface

class Iterator {
constructor(collection) {
this.collection = collection;
this.index = 0;
}

next() {
const item = this.collection[this.index];
this.index++;
return item;
}

hasNext() {
return this.index < this.collection.length;
}
}

// Concrete Aggregate
class ListAggregate {
constructor() {
this.items = [];
}

addItem(item) {
this.items.push(item);
}

createIterator() {
return new Iterator(this.items);
}
}

// Client code
const aggregate = new ListAggregate();
aggregate.addItem("Item 1");
aggregate.addItem("Item 2");

const iterator = aggregate.createIterator();

while (iterator.hasNext()) {
console.log(iterator.next());
}

No comments:

Post a Comment