tinyqueue.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global = global || self, global.TinyQueue = factory());
  5. }(this, function () { 'use strict';
  6. var TinyQueue = function TinyQueue(data, compare) {
  7. if ( data === void 0 ) data = [];
  8. if ( compare === void 0 ) compare = defaultCompare;
  9. this.data = data;
  10. this.length = this.data.length;
  11. this.compare = compare;
  12. if (this.length > 0) {
  13. for (var i = (this.length >> 1) - 1; i >= 0; i--) { this._down(i); }
  14. }
  15. };
  16. TinyQueue.prototype.push = function push (item) {
  17. this.data.push(item);
  18. this.length++;
  19. this._up(this.length - 1);
  20. };
  21. TinyQueue.prototype.pop = function pop () {
  22. if (this.length === 0) { return undefined; }
  23. var top = this.data[0];
  24. var bottom = this.data.pop();
  25. this.length--;
  26. if (this.length > 0) {
  27. this.data[0] = bottom;
  28. this._down(0);
  29. }
  30. return top;
  31. };
  32. TinyQueue.prototype.peek = function peek () {
  33. return this.data[0];
  34. };
  35. TinyQueue.prototype._up = function _up (pos) {
  36. var ref = this;
  37. var data = ref.data;
  38. var compare = ref.compare;
  39. var item = data[pos];
  40. while (pos > 0) {
  41. var parent = (pos - 1) >> 1;
  42. var current = data[parent];
  43. if (compare(item, current) >= 0) { break; }
  44. data[pos] = current;
  45. pos = parent;
  46. }
  47. data[pos] = item;
  48. };
  49. TinyQueue.prototype._down = function _down (pos) {
  50. var ref = this;
  51. var data = ref.data;
  52. var compare = ref.compare;
  53. var halfLength = this.length >> 1;
  54. var item = data[pos];
  55. while (pos < halfLength) {
  56. var left = (pos << 1) + 1;
  57. var best = data[left];
  58. var right = left + 1;
  59. if (right < this.length && compare(data[right], best) < 0) {
  60. left = right;
  61. best = data[right];
  62. }
  63. if (compare(best, item) >= 0) { break; }
  64. data[pos] = best;
  65. pos = left;
  66. }
  67. data[pos] = item;
  68. };
  69. function defaultCompare(a, b) {
  70. return a < b ? -1 : a > b ? 1 : 0;
  71. }
  72. return TinyQueue;
  73. }));