TupleQueue.js 1.3 KB

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