-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
61 lines (48 loc) · 1.2 KB
/
app.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
59
60
61
interface IteratorInterface<T> {
hasNext: () => boolean;
next: () => T | null;
}
class IteratorArray implements IteratorInterface<number> {
private index = 0;
private array: number[];
constructor(array: number[]) {
this.array = array;
}
hasNext() {
return this.index < this.array.length;
}
next() {
return this.hasNext() ? this.array[this.index++] : null;
}
}
class ObjectIterator
implements IteratorInterface<{ key: string; value: number }>
{
private index = 0;
private keys: string[];
private object: { [key: string]: number };
constructor(object: { [key: string]: number }) {
this.object = object;
this.keys = Object.keys(object);
}
hasNext() {
return this.index < this.keys.length;
}
next() {
if (this.hasNext()) {
const key = this.keys[this.index++];
return { key, value: this.object[key] };
}
return null;
}
}
(() => {
const iteratorArray = new IteratorArray([1, 2, 3, 4, 5]);
while (iteratorArray.hasNext()) {
console.log(iteratorArray.next());
}
const objectIterator = new ObjectIterator({ john: 0, doe: 1, jane: 2 });
while (objectIterator.hasNext()) {
console.log(objectIterator.next());
}
})();