-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
SimulatedClock.ts
83 lines (76 loc) · 1.97 KB
/
SimulatedClock.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
82
83
import { Clock } from './system.ts';
export interface SimulatedClock extends Clock {
start(speed: number): void;
increment(ms: number): void;
set(ms: number): void;
}
interface SimulatedTimeout {
start: number;
timeout: number;
fn: (...args: any[]) => void;
}
export class SimulatedClock implements SimulatedClock {
private timeouts: Map<number, SimulatedTimeout> = new Map();
private _now: number = 0;
private _id: number = 0;
private _flushing = false;
private _flushingInvalidated = false;
public now() {
return this._now;
}
private getId() {
return this._id++;
}
public setTimeout(fn: (...args: any[]) => void, timeout: number) {
this._flushingInvalidated = this._flushing;
const id = this.getId();
this.timeouts.set(id, {
start: this.now(),
timeout,
fn
});
return id;
}
public clearTimeout(id: number) {
this._flushingInvalidated = this._flushing;
this.timeouts.delete(id);
}
public set(time: number) {
if (this._now > time) {
throw new Error('Unable to travel back in time');
}
this._now = time;
this.flushTimeouts();
}
private flushTimeouts() {
if (this._flushing) {
this._flushingInvalidated = true;
return;
}
this._flushing = true;
const sorted = [...this.timeouts].sort(
([_idA, timeoutA], [_idB, timeoutB]) => {
const endA = timeoutA.start + timeoutA.timeout;
const endB = timeoutB.start + timeoutB.timeout;
return endB > endA ? -1 : 1;
}
);
for (const [id, timeout] of sorted) {
if (this._flushingInvalidated) {
this._flushingInvalidated = false;
this._flushing = false;
this.flushTimeouts();
return;
}
if (this.now() - timeout.start >= timeout.timeout) {
this.timeouts.delete(id);
timeout.fn.call(null);
}
}
this._flushing = false;
}
public increment(ms: number): void {
this._now += ms;
this.flushTimeouts();
}
}