-
Notifications
You must be signed in to change notification settings - Fork 2
/
Iterator.ts
58 lines (49 loc) · 1.08 KB
/
Iterator.ts
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
interface MyIterator {
next(): any;
hasNext(): boolean;
}
interface Aggregator {
createIterator(): MyIterator;
}
class ConcreteIterator implements MyIterator {
private collection: any[] = [];
private position: number = 0;
constructor(collection: any[]) {
this.collection = collection;
}
public next(): any {
// Error handling is left out
var result = this.collection[this.position];
this.position += 1;
return result;
}
public hasNext(): boolean {
return this.position < this.collection.length;
}
}
class Numbers implements Aggregator {
private collection: number[] = [];
constructor(collection: number[]) {
this.collection = collection;
}
public createIterator(): MyIterator {
return new ConcreteIterator(this.collection);
}
}
// USAGE:
var nArray = [1, 7, 21, 657, 3, 2, 765, 13, 65],
numbers: Numbers = new Numbers(nArray),
it: MyIterator = numbers.createIterator();
while (it.hasNext()) {
console.log(it.next());
}
// OUTPUT:
// 1
// 7
// 21
// 657
// 3
// 2
// 765
// 13
// 65