X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fqueue.ts;h=86b69051174672a92c158317f84beb1874cebf07;hb=b4213b7fc45201c5a38f2615289c569b679a15b7;hp=11766e4e9109dc4356be0a4b589ee5e5ed9b7bd3;hpb=4d8bf9e40e07bd233be4494fda4e4270fdd8a355;p=poolifier.git diff --git a/src/queue.ts b/src/queue.ts index 11766e4e..86b69051 100644 --- a/src/queue.ts +++ b/src/queue.ts @@ -1,27 +1,61 @@ +// Copyright Jerome Benoit. 2021-2023. All Rights Reserved. + /** * Queue + * + * @typeParam T - Type of queue items. */ export class Queue { private items: Record private head: number private tail: number + private max: number public constructor () { this.items = {} this.head = 0 this.tail = 0 + this.max = 0 } + /** + * Get the size of the queue. + * + * @returns The size of the queue. + * @readonly + */ public get size (): number { return this.tail - this.head } + /** + * Get the maximum size of the queue. + * + * @returns The maximum size of the queue. + * @readonly + */ + public get maxSize (): number { + return this.max + } + + /** + * Enqueue an item. + * + * @param item - Item to enqueue. + * @returns The new size of the queue. + */ public enqueue (item: T): number { this.items[this.tail] = item this.tail++ + if (this.size > this.max) this.max = this.size return this.size } + /** + * Dequeue an item. + * + * @returns The dequeued item or `undefined` if the queue is empty. + */ public dequeue (): T | undefined { if (this.size <= 0) return undefined const item = this.items[this.head] @@ -34,4 +68,12 @@ export class Queue { } return item } + + /** + * Peek at the first item. + */ + public peek (): T | undefined { + if (this.size <= 0) return undefined + return this.items[this.head] + } }