-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathSentinelIterator.ts
49 lines (41 loc) · 1.19 KB
/
SentinelIterator.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
import { ISentinelAddress } from "./types";
function isSentinelEql(
a: Partial<ISentinelAddress>,
b: Partial<ISentinelAddress>
): boolean {
return (
(a.host || "127.0.0.1") === (b.host || "127.0.0.1") &&
(a.port || 26379) === (b.port || 26379)
);
}
export default class SentinelIterator
implements Iterator<Partial<ISentinelAddress>> {
private cursor: number = 0;
constructor(private sentinels: Array<Partial<ISentinelAddress>>) {}
next() {
const done = this.cursor >= this.sentinels.length;
return { done, value: done ? undefined : this.sentinels[this.cursor++] };
}
reset(moveCurrentEndpointToFirst: boolean): void {
if (
moveCurrentEndpointToFirst &&
this.sentinels.length > 1 &&
this.cursor !== 1
) {
this.sentinels.unshift(...this.sentinels.splice(this.cursor - 1));
}
this.cursor = 0;
}
add(sentinel: ISentinelAddress): boolean {
for (let i = 0; i < this.sentinels.length; i++) {
if (isSentinelEql(sentinel, this.sentinels[i])) {
return false;
}
}
this.sentinels.push(sentinel);
return true;
}
toString(): string {
return `${JSON.stringify(this.sentinels)} @${this.cursor}`;
}
}