1 | import { __spreadArray, __read } from './_virtual/_tslib.js';
|
2 |
|
3 | var SimulatedClock =
|
4 |
|
5 |
|
6 |
|
7 | function () {
|
8 | function SimulatedClock() {
|
9 | this.timeouts = new Map();
|
10 | this._now = 0;
|
11 | this._id = 0;
|
12 | }
|
13 |
|
14 | SimulatedClock.prototype.now = function () {
|
15 | return this._now;
|
16 | };
|
17 |
|
18 | SimulatedClock.prototype.getId = function () {
|
19 | return this._id++;
|
20 | };
|
21 |
|
22 | SimulatedClock.prototype.setTimeout = function (fn, timeout) {
|
23 | var id = this.getId();
|
24 | this.timeouts.set(id, {
|
25 | start: this.now(),
|
26 | timeout: timeout,
|
27 | fn: fn
|
28 | });
|
29 | return id;
|
30 | };
|
31 |
|
32 | SimulatedClock.prototype.clearTimeout = function (id) {
|
33 | this.timeouts.delete(id);
|
34 | };
|
35 |
|
36 | SimulatedClock.prototype.set = function (time) {
|
37 | if (this._now > time) {
|
38 | throw new Error('Unable to travel back in time');
|
39 | }
|
40 |
|
41 | this._now = time;
|
42 | this.flushTimeouts();
|
43 | };
|
44 |
|
45 | SimulatedClock.prototype.flushTimeouts = function () {
|
46 | var _this = this;
|
47 |
|
48 | __spreadArray([], __read(this.timeouts), false).sort(function (_a, _b) {
|
49 | var _c = __read(_a, 2);
|
50 | _c[0];
|
51 | var timeoutA = _c[1];
|
52 |
|
53 | var _d = __read(_b, 2);
|
54 | _d[0];
|
55 | var timeoutB = _d[1];
|
56 |
|
57 | var endA = timeoutA.start + timeoutA.timeout;
|
58 | var endB = timeoutB.start + timeoutB.timeout;
|
59 | return endB > endA ? -1 : 1;
|
60 | }).forEach(function (_a) {
|
61 | var _b = __read(_a, 2),
|
62 | id = _b[0],
|
63 | timeout = _b[1];
|
64 |
|
65 | if (_this.now() - timeout.start >= timeout.timeout) {
|
66 | _this.timeouts.delete(id);
|
67 |
|
68 | timeout.fn.call(null);
|
69 | }
|
70 | });
|
71 | };
|
72 |
|
73 | SimulatedClock.prototype.increment = function (ms) {
|
74 | this._now += ms;
|
75 | this.flushTimeouts();
|
76 | };
|
77 |
|
78 | return SimulatedClock;
|
79 | }();
|
80 |
|
81 | export { SimulatedClock };
|