2
0

Queue.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. export class SimpleQueue<T> {
  2. private arr: T[] = []; // Array to store data and maintain insertion order
  3. public isObseleted: boolean = false; // Flag to indicate if queue is abandoned
  4. // Method to add an item to the queue
  5. enqueue(item: T) {
  6. this.arr.push(item);
  7. }
  8. // Method to remove and return the earliest inserted item from the queue
  9. dequeue(): T | undefined {
  10. return this.arr.shift();
  11. }
  12. // Method to get the latest inserted item in the queue
  13. getLatest(): T | undefined {
  14. return this.arr[this.arr.length - 1];
  15. }
  16. // Method to get the earliest inserted item in the queue
  17. getEarliest(): T | undefined {
  18. return this.arr[0];
  19. }
  20. // Method to get the size of the queue
  21. size(): number {
  22. return this.arr.length;
  23. }
  24. // Method to check if the queue is empty
  25. isEmpty(): boolean {
  26. return this.arr.length === 0;
  27. }
  28. // Method to clear the queue
  29. stop() {
  30. this.arr = [];
  31. this.isObseleted = true; // Reset the abandoned flag
  32. }
  33. // Method to execute each item in the queue sequentially until the queue is empty
  34. async executeNext(
  35. callback: (items: T[], q: SimpleQueue<T>) => Promise<void>,
  36. count: number = 1
  37. ) {
  38. if (this.isObseleted) {
  39. return; // If abandoned flag is set, return
  40. }
  41. // items to process
  42. const items: T[] = [];
  43. while (!this.isEmpty() && items.length < count) {
  44. const item = this.dequeue();
  45. if (item !== undefined) {
  46. items.push(item);
  47. }
  48. }
  49. // execute callback
  50. if (items.length > 0) {
  51. await callback(items, this);
  52. }
  53. }
  54. }