TupleQueue.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const TupleSet = require("./TupleSet");
  7. /**
  8. * @template T
  9. * @template V
  10. */
  11. class TupleQueue {
  12. /**
  13. * @param {Iterable<[T, V]>=} items The initial elements.
  14. */
  15. constructor(items) {
  16. /**
  17. * @private
  18. * @type {TupleSet<[T, V]>}
  19. */
  20. this._set = new TupleSet(items);
  21. /**
  22. * @private
  23. * @type {Iterator<[T, V]>}
  24. */
  25. this._iterator = this._set[Symbol.iterator]();
  26. }
  27. /**
  28. * Returns the number of elements in this queue.
  29. * @returns {number} The number of elements in this queue.
  30. */
  31. get length() {
  32. return this._set.size;
  33. }
  34. /**
  35. * Appends the specified element to this queue.
  36. * @param {[T, V]} item The element to add.
  37. * @returns {void}
  38. */
  39. enqueue(...item) {
  40. this._set.add(...item);
  41. }
  42. /**
  43. * Retrieves and removes the head of this queue.
  44. * @returns {[T, V] | undefined} The head of the queue of `undefined` if this queue is empty.
  45. */
  46. dequeue() {
  47. const result = this._iterator.next();
  48. if (result.done) {
  49. if (this._set.size > 0) {
  50. this._iterator = this._set[Symbol.iterator]();
  51. const value = /** @type {[T, V]} */ (this._iterator.next().value);
  52. this._set.delete(...value);
  53. return value;
  54. }
  55. return;
  56. }
  57. this._set.delete(.../** @type {[T, V]} */ (result.value));
  58. return result.value;
  59. }
  60. }
  61. module.exports = TupleQueue;