-
Notifications
You must be signed in to change notification settings - Fork 0
/
IterableDoubleLinkedList.ts
75 lines (71 loc) · 1.99 KB
/
IterableDoubleLinkedList.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import IBiDirectIterator from "../../../types/IBiDirectIterator";
import IBiDirectIterable from "../../../types/IBiDirectIterable";
import IsNotFoundException from "../../../exceptions/IsNotFoundException";
import DoubleLinkedNode from "./DoubleLinkedNode";
import DoubleLinkedList from "./DoubleLinkedList";
/**
* @inheritDoc
*/
export default class IterableDoubleLinkedList<T>
extends DoubleLinkedList<T>
implements IBiDirectIterable<T> {
/**
* @inheritDoc
*/
public constructor(capacity?: number) {
super(capacity);
}
/**
* List iterator
* @throws {CollectionIsEmptyException} when list is empty
* @throws {IndexOutOfBoundsException} when given index is out of range
*/
public iterator(fromIndex = 0): IBiDirectIterator<T> {
const head = this._head;
const tail = this._tail;
let activeNode = this.getNodeByIndex(fromIndex) as DoubleLinkedNode<T>;
const iterator: IBiDirectIterator<T> = {
/**
* @inheritDoc
*/
current: () => {
return activeNode.data;
},
/**
* @inheritDoc
*/
hasNext(): boolean {
return Boolean(activeNode.next) && activeNode !== head;
},
/**
* @inheritDoc
*/
hasPrev(): boolean {
return Boolean(activeNode.prev) && activeNode !== tail;
},
/**
* @inheritDoc
* @throws {IsNotFoundException} when next element does not exist
*/
next: (): T => {
if (!iterator.hasNext()) {
throw new IsNotFoundException("Next element does not exist");
}
activeNode = activeNode.next!;
return activeNode.data;
},
/**
* @inheritDoc
* @throws {IsNotFoundException} when prev element does not exists
*/
prev: (): T => {
if (!iterator.hasPrev()) {
throw new IsNotFoundException("Prev element does not exist");
}
activeNode = activeNode.prev!;
return activeNode.data;
},
};
return iterator;
}
}