fifo.ts 945 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. class Node<T> {
  2. next?: Node<T>;
  3. constructor(public readonly value: T) {}
  4. }
  5. export default class FIFO<T> {
  6. private head?: Node<T>;
  7. private tail?: Node<T>;
  8. public $size = 0;
  9. constructor() {
  10. this.clear();
  11. }
  12. enqueue(value: T) {
  13. const node = new Node<T>(value);
  14. if (this.head) {
  15. this.tail!.next = node;
  16. this.tail = node;
  17. } else {
  18. this.head = node;
  19. this.tail = node;
  20. }
  21. this.$size++;
  22. }
  23. dequeue() {
  24. const current = this.head;
  25. if (!current) {
  26. return;
  27. }
  28. this.head = this.head!.next;
  29. this.$size--;
  30. return current.value;
  31. }
  32. peek() {
  33. return this.head?.value;
  34. }
  35. clear() {
  36. this.head = undefined;
  37. this.tail = undefined;
  38. this.$size = 0;
  39. }
  40. get size() {
  41. return this.$size;
  42. }
  43. *[Symbol.iterator]() {
  44. let current = this.head;
  45. while (current) {
  46. yield current.value;
  47. current = current.next;
  48. }
  49. }
  50. }