TupleQueue.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 {any[]} T
  9. */
  10. class TupleQueue {
  11. /**
  12. * @param {Iterable<T>=} items The initial elements.
  13. */
  14. constructor(items) {
  15. /** @private @type {TupleSet<T>} */
  16. this._set = new TupleSet(items);
  17. /** @private @type {Iterator<T>} */
  18. this._iterator = this._set[Symbol.iterator]();
  19. }
  20. /**
  21. * Returns the number of elements in this queue.
  22. * @returns {number} The number of elements in this queue.
  23. */
  24. get length() {
  25. return this._set.size;
  26. }
  27. /**
  28. * Appends the specified element to this queue.
  29. * @param {T} item The element to add.
  30. * @returns {void}
  31. */
  32. enqueue(...item) {
  33. this._set.add(...item);
  34. }
  35. /**
  36. * Retrieves and removes the head of this queue.
  37. * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty.
  38. */
  39. dequeue() {
  40. const result = this._iterator.next();
  41. if (result.done) {
  42. if (this._set.size > 0) {
  43. this._iterator = this._set[Symbol.iterator]();
  44. const value = this._iterator.next().value;
  45. this._set.delete(...value);
  46. return value;
  47. }
  48. return undefined;
  49. }
  50. this._set.delete(...result.value);
  51. return result.value;
  52. }
  53. }
  54. module.exports = TupleQueue;