X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fqueue.ts;h=7aad6d065ce6338129c70032b266ce5c6bcba600;hb=8a97042123ae9a0404637711b8da7c6e7e4424c7;hp=a2a613814e86dcd5ab13b7122d8c26a7e647d610;hpb=3db6a2b42ee697b6f587b0f41020771941a65e68;p=poolifier.git diff --git a/src/queue.ts b/src/queue.ts index a2a61381..7aad6d06 100644 --- a/src/queue.ts +++ b/src/queue.ts @@ -6,24 +6,18 @@ * @typeParam T - Type of queue items. */ export class Queue { - private items: Record - private head: number - private tail: number + private items: T[] + private offset: number + public size: number + public maxSize: number public constructor () { - this.items = {} - this.head = 0 - this.tail = 0 - } - - /** - * Get the size of the queue. - * - * @returns The size of the queue. - * @readonly - */ - public get size (): number { - return this.tail - this.head + this.items = [] + this.offset = 0 + /** The size of the queue. */ + this.size = 0 + /** The maximum size of the queue. */ + this.maxSize = 0 } /** @@ -33,27 +27,41 @@ export class Queue { * @returns The new size of the queue. */ public enqueue (item: T): number { - this.items[this.tail] = item - this.tail++ + this.items.push(item) + ++this.size + if (this.size > this.maxSize) { + this.maxSize = this.size + } return this.size } /** * Dequeue an item. * - * @returns The dequeued item. - * @returns `undefined` if the queue is empty. + * @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] - this.head++ - if (this.head === this.tail) { - this.head = 0 - this.tail = 0 + if (this.size <= 0) { + return undefined + } + const item = this.items[this.offset] + if (++this.offset * 2 >= this.items.length) { + this.items = this.items.slice(this.offset) + this.offset = 0 } + --this.size return item } + + /** + * Peek at the first item. + * + * @returns The first item or `undefined` if the queue is empty. + */ + public peek (): T | undefined { + if (this.size <= 0) { + return undefined + } + return this.items[this.offset] + } }