priority-queue.js 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const lower_bound_1 = require("./lower-bound");
  4. class PriorityQueue {
  5. constructor() {
  6. this._queue = [];
  7. }
  8. enqueue(run, options) {
  9. options = Object.assign({ priority: 0 }, options);
  10. const element = {
  11. priority: options.priority,
  12. run
  13. };
  14. if (this.size && this._queue[this.size - 1].priority >= options.priority) {
  15. this._queue.push(element);
  16. return;
  17. }
  18. const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority);
  19. this._queue.splice(index, 0, element);
  20. }
  21. dequeue() {
  22. const item = this._queue.shift();
  23. return item === null || item === void 0 ? void 0 : item.run;
  24. }
  25. filter(options) {
  26. return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run);
  27. }
  28. get size() {
  29. return this._queue.length;
  30. }
  31. }
  32. exports.default = PriorityQueue;