index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. How it works:
  3. `this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
  4. */
  5. class Node {
  6. value;
  7. next;
  8. constructor(value) {
  9. this.value = value;
  10. }
  11. }
  12. export default class Queue {
  13. #head;
  14. #tail;
  15. #size;
  16. constructor() {
  17. this.clear();
  18. }
  19. enqueue(value) {
  20. const node = new Node(value);
  21. if (this.#head) {
  22. this.#tail.next = node;
  23. this.#tail = node;
  24. } else {
  25. this.#head = node;
  26. this.#tail = node;
  27. }
  28. this.#size++;
  29. }
  30. dequeue() {
  31. const current = this.#head;
  32. if (!current) {
  33. return;
  34. }
  35. this.#head = this.#head.next;
  36. this.#size--;
  37. return current.value;
  38. }
  39. clear() {
  40. this.#head = undefined;
  41. this.#tail = undefined;
  42. this.#size = 0;
  43. }
  44. get size() {
  45. return this.#size;
  46. }
  47. * [Symbol.iterator]() {
  48. let current = this.#head;
  49. while (current) {
  50. yield current.value;
  51. current = current.next;
  52. }
  53. }
  54. }