Queue.js 1.0 KB

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