PriorityQueue.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. "use strict";
  2. Object.defineProperty(exports, "t", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _ContainerBase = require("../ContainerBase");
  7. class PriorityQueue extends _ContainerBase.Base {
  8. constructor(t = [], s = ((t, s) => {
  9. if (t > s) return -1;
  10. if (t < s) return 1;
  11. return 0;
  12. }), i = true) {
  13. super();
  14. this.p = s;
  15. if (Array.isArray(t)) {
  16. this._ = i ? [ ...t ] : t;
  17. } else {
  18. this._ = [];
  19. t.forEach((t => this._.push(t)));
  20. }
  21. this.o = this._.length;
  22. const e = this.o >> 1;
  23. for (let t = this.o - 1 >> 1; t >= 0; --t) {
  24. this.v(t, e);
  25. }
  26. }
  27. B(t) {
  28. const s = this._[t];
  29. while (t > 0) {
  30. const i = t - 1 >> 1;
  31. const e = this._[i];
  32. if (this.p(e, s) <= 0) break;
  33. this._[t] = e;
  34. t = i;
  35. }
  36. this._[t] = s;
  37. }
  38. v(t, s) {
  39. const i = this._[t];
  40. while (t < s) {
  41. let s = t << 1 | 1;
  42. const e = s + 1;
  43. let h = this._[s];
  44. if (e < this.o && this.p(h, this._[e]) > 0) {
  45. s = e;
  46. h = this._[e];
  47. }
  48. if (this.p(h, i) >= 0) break;
  49. this._[t] = h;
  50. t = s;
  51. }
  52. this._[t] = i;
  53. }
  54. clear() {
  55. this.o = 0;
  56. this._.length = 0;
  57. }
  58. push(t) {
  59. this._.push(t);
  60. this.B(this.o);
  61. this.o += 1;
  62. }
  63. pop() {
  64. if (!this.o) return;
  65. const t = this._.pop();
  66. this.o -= 1;
  67. if (this.o) {
  68. this._[0] = t;
  69. this.v(0, this.o >> 1);
  70. }
  71. }
  72. top() {
  73. return this._[0];
  74. }
  75. find(t) {
  76. return this._.indexOf(t) >= 0;
  77. }
  78. remove(t) {
  79. const s = this._.indexOf(t);
  80. if (s < 0) return false;
  81. if (s === 0) {
  82. this.pop();
  83. } else if (s === this.o - 1) {
  84. this._.pop();
  85. this.o -= 1;
  86. } else {
  87. this._.splice(s, 1, this._.pop());
  88. this.o -= 1;
  89. this.B(s);
  90. this.v(s, this.o >> 1);
  91. }
  92. return true;
  93. }
  94. updateItem(t) {
  95. const s = this._.indexOf(t);
  96. if (s < 0) return false;
  97. this.B(s);
  98. this.v(s, this.o >> 1);
  99. return true;
  100. }
  101. toArray() {
  102. return [ ...this._ ];
  103. }
  104. }
  105. var _default = PriorityQueue;
  106. exports.default = _default;