PriorityQueue.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. "use strict";
  2. const Queue = require("./Queue");
  3. /**
  4. * @class
  5. * @private
  6. */
  7. class PriorityQueue {
  8. constructor(size) {
  9. this._size = Math.max(+size | 0, 1);
  10. /** @type {Queue[]} */
  11. this._slots = [];
  12. // initialize arrays to hold queue elements
  13. for (let i = 0; i < this._size; i++) {
  14. this._slots.push(new Queue());
  15. }
  16. }
  17. get length() {
  18. let _length = 0;
  19. for (let i = 0, slots = this._slots.length; i < slots; i++) {
  20. _length += this._slots[i].length;
  21. }
  22. return _length;
  23. }
  24. enqueue(obj, priority) {
  25. // Convert to integer with a default value of 0.
  26. priority = (priority && +priority | 0) || 0;
  27. if (priority) {
  28. if (priority < 0 || priority >= this._size) {
  29. priority = this._size - 1;
  30. // put obj at the end of the line
  31. }
  32. }
  33. this._slots[priority].push(obj);
  34. }
  35. dequeue() {
  36. for (let i = 0, sl = this._slots.length; i < sl; i += 1) {
  37. if (this._slots[i].length) {
  38. return this._slots[i].shift();
  39. }
  40. }
  41. return;
  42. }
  43. get head() {
  44. for (let i = 0, sl = this._slots.length; i < sl; i += 1) {
  45. if (this._slots[i].length > 0) {
  46. return this._slots[i].head;
  47. }
  48. }
  49. return;
  50. }
  51. get tail() {
  52. for (let i = this._slots.length - 1; i >= 0; i--) {
  53. if (this._slots[i].length > 0) {
  54. return this._slots[i].tail;
  55. }
  56. }
  57. return;
  58. }
  59. }
  60. module.exports = PriorityQueue;