-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
RandomIterator.ts
81 lines (80 loc) · 2.13 KB
/
RandomIterator.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
76
77
78
79
80
81
import { $checkWithinAccessParams } from '@/utils/checkParams.macro';
import { ContainerIterator, IteratorType } from '@/container/ContainerBase';
export abstract class RandomIterator<T> extends ContainerIterator<T> {
/**
* @internal
*/
_node: number;
/**
* @internal
*/
protected readonly _size: () => number;
/**
* @internal
*/
protected readonly _getElementByPos: (pos: number) => T;
/**
* @internal
*/
protected readonly _setElementByPos: (pos: number, element: T) => void;
pre: () => this;
next: () => this;
/**
* @internal
*/
constructor(
index: number,
size: () => number,
getElementByPos: (pos: number) => T,
setElementByPos: (pos: number, element: T) => void,
iteratorType?: IteratorType
) {
super(iteratorType);
this._node = index;
this._size = size;
this._getElementByPos = getElementByPos;
this._setElementByPos = setElementByPos;
if (this.iteratorType === IteratorType.NORMAL) {
this.pre = function () {
if (this._node === 0) {
throw new RangeError('Random iterator access denied!');
}
this._node -= 1;
return this;
};
this.next = function () {
if (this._node === this._size()) {
throw new RangeError('Random Iterator access denied!');
}
this._node += 1;
return this;
};
} else {
this.pre = function () {
if (this._node === this._size() - 1) {
throw new RangeError('Random iterator access denied!');
}
this._node += 1;
return this;
};
this.next = function () {
if (this._node === -1) {
throw new RangeError('Random iterator access denied!');
}
this._node -= 1;
return this;
};
}
}
get pointer() {
$checkWithinAccessParams!(this._node, 0, this._size() - 1);
return this._getElementByPos(this._node);
}
set pointer(newValue: T) {
$checkWithinAccessParams!(this._node, 0, this._size() - 1);
this._setElementByPos(this._node, newValue);
}
equals(obj: RandomIterator<T>) {
return this._node === obj._node;
}
}