Queue.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /**
  7. * FIFO queue that keeps items unique by storing them in insertion order inside
  8. * a `Set`.
  9. * @template T
  10. */
  11. class Queue {
  12. /**
  13. * Seeds the queue with an optional iterable of initial unique items.
  14. * @param {Iterable<T>=} items The initial elements.
  15. */
  16. constructor(items) {
  17. /**
  18. * @private
  19. * @type {Set<T>}
  20. */
  21. this._set = new Set(items);
  22. }
  23. /**
  24. * Returns the number of unique items currently waiting in the queue.
  25. * @returns {number} The number of elements in this queue.
  26. */
  27. get length() {
  28. return this._set.size;
  29. }
  30. /**
  31. * Enqueues an item, moving nothing if that value is already present.
  32. * @param {T} item The element to add.
  33. * @returns {void}
  34. */
  35. enqueue(item) {
  36. this._set.add(item);
  37. }
  38. /**
  39. * Removes and returns the oldest enqueued item.
  40. * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty.
  41. */
  42. dequeue() {
  43. const result = this._set[Symbol.iterator]().next();
  44. if (result.done) return;
  45. this._set.delete(result.value);
  46. return result.value;
  47. }
  48. }
  49. module.exports = Queue;