-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
traverse-state.ts
59 lines (52 loc) · 1.3 KB
/
traverse-state.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
/**
* An object used to track the state of a traversal, e.g. a `forEach`.
*/
export interface TraverseState {
/**
* Returns true if the traversal has been halted by the user.
*/
readonly halted: boolean;
/**
* Returns the current index of the traversal.
*/
readonly currentIndex: number;
/**
* Increases the `currentIndex` of this traversal
* @returns the next index that the traversal should use
*/
nextIndex(): number;
/**
* Sets the `halted` value to true.
*/
halt(): void;
/**
* Sets the `halted` value to false, and resets the `currentIndex`
* value to its start value.
*/
reset(): void;
}
class TraverseStateImpl implements TraverseState {
currentIndex: number;
halted = false;
constructor(readonly startIndex: number) {
this.currentIndex = startIndex;
}
nextIndex(): number {
return this.currentIndex++;
}
readonly halt = (): void => {
this.halted = true;
};
reset(): void {
this.currentIndex = this.startIndex;
this.halted = false;
}
}
/**
* Returns a new `TraverseState` instance, using optionally given `startIndex` as a start
* index value.
* @param startIndex - (default: 0) the start index to use
*/
export function TraverseState(startIndex = 0): TraverseState {
return new TraverseStateImpl(startIndex);
}