-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample02.ts
More file actions
42 lines (32 loc) · 947 Bytes
/
example02.ts
File metadata and controls
42 lines (32 loc) · 947 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
interface Iterator<T> {
next(): { value: T | null; done: boolean };
}
class ItemCollection<T> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
createIterator(): Iterator<T> {
return new ArrayIterator<T>(this.items);
}
}
class ArrayIterator<T> implements Iterator<T> {
private index = 0;
constructor(private collection: T[]) { }
next(): { value: T | null; done: boolean } {
if (this.index < this.collection.length) {
return { value: this.collection[this.index++], done: false };
}
return { value: null, done: true };
}
}
const collection = new ItemCollection<string>();
collection.add("🟡");
collection.add("🟠");
collection.add("🟣");
const iterator = collection.createIterator();
let result = iterator.next();
while (!result.done) {
console.log("Елемент:", result.value);
result = iterator.next();
}