UNPKG

1.54 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.Queue = void 0;
7/**
8 * A simple queue with optional priority.
9 */
10class Queue {
11 /**
12 * Queue data.
13 */
14 _queue_ = [];
15
16 /**
17 * Queue constructor.
18 */
19 constructor() {}
20
21 /**
22 * Get size of queue.
23 *
24 * @returns Total callbacks in queue.
25 */
26 get size() {
27 return this._queue_.length;
28 }
29
30 /**
31 * Clear queue.
32 */
33 clear() {
34 this._queue_ = [];
35 }
36
37 /**
38 * Enqueue callback.
39 *
40 * @param handler Callback function.
41 * @param priority Callback priority.
42 */
43 push(handler, priority = 0) {
44 const queue = this._queue_;
45 let index = 0;
46 for (let i = queue.length; i--;) {
47 if (queue[i].priority < priority) {
48 index = i + 1;
49 break;
50 }
51 }
52 queue.splice(index, 0, {
53 priority,
54 handler
55 });
56 }
57
58 /**
59 * Pop callback off queue.
60 *
61 * @returns Callback function or null if empty.
62 */
63 pop() {
64 const entry = this._queue_.pop();
65 return entry ? entry.handler : null;
66 }
67
68 /**
69 * Shift callback off queue.
70 *
71 * @returns Callback function or null if empty.
72 */
73 shift() {
74 const entry = this._queue_.shift();
75 return entry ? entry.handler : null;
76 }
77
78 /**
79 * Run queue.
80 */
81 async run() {
82 for (;;) {
83 const entry = this.pop();
84 if (!entry) {
85 break;
86 }
87
88 // eslint-disable-next-line no-await-in-loop
89 await entry();
90 }
91 }
92}
93exports.Queue = Queue;
94//# sourceMappingURL=queue.js.map
\No newline at end of file