You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
940 B

4 years ago
  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;