Queue.js 940 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. /**
  3. * @template T
  4. */
  5. class Queue {
  6. /**
  7. * @param {Iterable<T>=} items The initial elements.
  8. */
  9. constructor(items) {
  10. /** @private @type {Set<T>} */
  11. this.set = new Set(items);
  12. /** @private @type {Iterator<T>} */
  13. this.iterator = this.set[Symbol.iterator]();
  14. }
  15. /**
  16. * Returns the number of elements in this queue.
  17. * @returns {number} The number of elements in this queue.
  18. */
  19. get length() {
  20. return this.set.size;
  21. }
  22. /**
  23. * Appends the specified element to this queue.
  24. * @param {T} item The element to add.
  25. * @returns {void}
  26. */
  27. enqueue(item) {
  28. this.set.add(item);
  29. }
  30. /**
  31. * Retrieves and removes the head of this queue.
  32. * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty.
  33. */
  34. dequeue() {
  35. const result = this.iterator.next();
  36. if (result.done) return undefined;
  37. this.set.delete(result.value);
  38. return result.value;
  39. }
  40. }
  41. module.exports = Queue;