Queue.js 1.0 KB

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