X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fqueue.ts;h=86b69051174672a92c158317f84beb1874cebf07;hb=0aa458de579cfd6cf9000458f0d40bb54fa0de46;hp=5cc13fcd27e7ea86e3bf504d5b5e3a110665b85d;hpb=29ee7e9a3f325f87d889ef09ffc1eea4916a782f;p=poolifier.git diff --git a/src/queue.ts b/src/queue.ts index 5cc13fcd..86b69051 100644 --- a/src/queue.ts +++ b/src/queue.ts @@ -1,25 +1,63 @@ +// 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 - constructor () { + 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 } - enqueue (item: T): number { + /** + * 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++ - return this.size() + if (this.size > this.max) this.max = this.size + return this.size } - dequeue (): T | undefined { - if (this.size() <= 0) return undefined + /** + * 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] // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.items[this.head] @@ -31,7 +69,11 @@ export class Queue { return item } - size (): number { - return this.tail - this.head + /** + * Peek at the first item. + */ + public peek (): T | undefined { + if (this.size <= 0) return undefined + return this.items[this.head] } }