UNPKG

1.18 kBJavaScriptView Raw
1import lowerBound from './lower-bound.js';
2export default class PriorityQueue {
3 constructor() {
4 Object.defineProperty(this, "_queue", {
5 enumerable: true,
6 configurable: true,
7 writable: true,
8 value: []
9 });
10 }
11 enqueue(run, options) {
12 var _a;
13 options = {
14 priority: 0,
15 ...options
16 };
17 const element = {
18 priority: options.priority,
19 run
20 };
21 if (this.size && ((_a = this._queue[this.size - 1]) === null || _a === void 0 ? void 0 : _a.priority) >= options.priority) {
22 this._queue.push(element);
23 return;
24 }
25 const index = lowerBound(this._queue, element, (a, b) => b.priority - a.priority);
26 this._queue.splice(index, 0, element);
27 }
28 dequeue() {
29 const item = this._queue.shift();
30 return item === null || item === void 0 ? void 0 : item.run;
31 }
32 filter(options) {
33 return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run);
34 }
35 get size() {
36 return this._queue.length;
37 }
38}