queue.ts 551 B

1234567891011121314151617181920212223242526272829303132
  1. export class Queue<T> {
  2. private items: T[] = [];
  3. enqueue(item: T) {
  4. this.items.push(item);
  5. }
  6. dequeue(): T | undefined {
  7. return this.items.shift();
  8. }
  9. peek(): T | undefined {
  10. return this.items[0];
  11. }
  12. isEmpty(): boolean {
  13. return this.items.length === 0;
  14. }
  15. size(): number {
  16. return this.items.length;
  17. }
  18. clear() {
  19. this.items = [];
  20. }
  21. // Add forEach to iterate over the queue's items in order
  22. forEach(callback: (item: T, index: number, array: T[]) => void) {
  23. this.items.forEach(callback);
  24. }
  25. }