TupleQueue.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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, ...EXPECTED_ANY]>=} 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, ...EXPECTED_ANY]>}
  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, ...EXPECTED_ANY]} 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, ...EXPECTED_ANY] | 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 =
  52. /** @type {[T, V, ...EXPECTED_ANY]} */
  53. (this._iterator.next().value);
  54. this._set.delete(...value);
  55. return value;
  56. }
  57. return;
  58. }
  59. this._set.delete(.../** @type {[T, V, ...EXPECTED_ANY]} */ (result.value));
  60. return result.value;
  61. }
  62. }
  63. module.exports = TupleQueue;