refactor: factor out worker runtime getter
[poolifier.git] / src / queue.ts
1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 /**
4 * Queue
5 *
6 * @typeParam T - Type of queue items.
7 */
8 export class Queue<T> {
9 private items: Record<number, T>
10 private head: number
11 private tail: number
12
13 public constructor () {
14 this.items = {}
15 this.head = 0
16 this.tail = 0
17 }
18
19 /**
20 * Get the size of the queue.
21 *
22 * @returns The size of the queue.
23 * @readonly
24 */
25 public get size (): number {
26 return this.tail - this.head
27 }
28
29 /**
30 * Enqueue an item.
31 *
32 * @param item - Item to enqueue.
33 * @returns The new size of the queue.
34 */
35 public enqueue (item: T): number {
36 this.items[this.tail] = item
37 this.tail++
38 return this.size
39 }
40
41 /**
42 * Dequeue an item.
43 *
44 * @returns The dequeued item or `undefined` if the queue is empty.
45 */
46 public dequeue (): T | undefined {
47 if (this.size <= 0) return undefined
48 const item = this.items[this.head]
49 // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
50 delete this.items[this.head]
51 this.head++
52 if (this.head === this.tail) {
53 this.head = 0
54 this.tail = 0
55 }
56 return item
57 }
58
59 /**
60 * Peek at the first item.
61 */
62 public peek (): T | undefined {
63 if (this.size <= 0) return undefined
64 return this.items[this.head]
65 }
66 }