/** * Queue helpers provide fixed-capacity FIFO storage with predictable O(1) * enqueue and dequeue work. * * A plain array is fine for append-only work. The trouble starts when you keep * removing from the front with `Array.shift()`, because every remaining element * has to be reindexed. The circular buffer here avoids that by moving `head` * and `tail` pointers around one fixed backing array. * * ```text * items: [A, B, C, ., .] * ^ ^ * head tail * * dequeue(A) -> head moves right * enqueue(D) -> tail writes into next slot * * items: [A, B, C, D, .] * ^ ^ * head tail * * when tail reaches capacity, it wraps back to 0 * ``` * * That wrap-around behavior is why replay buffers and hot-path event queues can * grow and shrink without paying O(n) array-shift costs. * * @module */ /////////////////////// // Core Data Types // /////////////////////// /** * Represents a circular buffer-based queue for efficient FIFO operations. * * @template T - The type of elements stored in the queue */ export interface Queue { /** The backing array that holds queue elements */ items: T[]; /** Index pointing to the front element (next to dequeue) */ head: number; /** Index pointing to where the next element will be added */ tail: number; /** Current number of elements in the queue */ size: number; /** Maximum capacity of the queue */ capacity: number; } /** * Advances a circular-buffer index by one slot and wraps back to `0` at the end. * * This keeps the same O(1) behavior as `% capacity`, but avoids paying modulo * cost for arbitrary capacities in the queue hot path. It is private because * it only exists to speed up internal queue pointer movement. */ function advanceIndex(index: number, capacity: number): number { const next = index + 1; return next === capacity ? 0 : next; } //////////////////////////// // Factory & Core Setup // //////////////////////////// /** * Creates a new empty queue with the specified capacity. * * The queue uses a circular buffer internally, which means operations * like enqueue and dequeue run in constant O(1) time regardless of * queue size. * * @param capacity - Maximum number of elements the queue can hold (default: 1000) * @returns A new empty queue ready for use * * @example * ``` * const messageQueue = createQueue(50); // for messages * const numberQueue = createQueue(); // uses default capacity * ``` */ export function createQueue(capacity: number = 1000): Queue { return { items: new Array(capacity), head: 0, tail: 0, size: 0, capacity, }; } ///////////////////////// // Core Queue Operations // ///////////////////////// /** * Adds an element to the back of the queue (FIFO: last in, first served). * Runs in O(1) constant time. * * @param queue - The target queue * @param item - Element to add to the queue * @throws Error if the queue is at capacity * * @example * ``` * enqueue(userQueue, { id: 123, name: 'Alice' }); * enqueue(userQueue, { id: 124, name: 'Bob' }); * ``` */ export function enqueue(queue: Queue, item: T): void { if (isFull(queue)) { throw new Error( `Queue overflow: cannot add item, capacity ${queue.capacity} reached`, ); } queue.items[queue.tail] = item; queue.tail = advanceIndex(queue.tail, queue.capacity); queue.size++; } /** * Removes and returns the front element from the queue (FIFO: first in, first out). * Runs in O(1) constant time. * * @param queue - The target queue * @returns The front element, or undefined if queue is empty * * @example * ``` * const nextTask = dequeue(taskQueue); * if (nextTask) { * console.log('Processing:', nextTask); * } * ``` */ export function dequeue(queue: Queue): T | undefined { if (isEmpty(queue)) { return undefined; } const item = queue.items[queue.head]; queue.items[queue.head] = undefined as unknown as T; // help garbage collector queue.head = advanceIndex(queue.head, queue.capacity); queue.size--; return item; } /** * Returns the front element without removing it from the queue. * Useful for checking what's next without consuming it. * Runs in O(1) constant time. * * @param queue - The target queue * @returns The front element, or undefined if queue is empty * * @example * ``` * const nextInLine = peek(queue); * if (nextInLine?.priority === 'urgent') { * // handle urgent task immediately * dequeue(queue); * } * ``` */ export function peek(queue: Queue): T | undefined { return isEmpty(queue) ? undefined : queue.items[queue.head]; } //////////////////////////////// // Utility & Status Functions // //////////////////////////////// /** * Checks if the queue contains no elements. * * @param queue - The target queue * @returns true if the queue is empty, false otherwise */ export function isEmpty(queue: Queue): boolean { return queue.size === 0; } /** * Checks if the queue has reached its maximum capacity. * * @param queue - The target queue * @returns true if the queue is full, false otherwise */ export function isFull(queue: Queue): boolean { return queue.size >= queue.capacity; } /** * Returns the current number of elements in the queue. * * @param queue - The target queue * @returns Current queue size (0 to capacity) */ export function getSize(queue: Queue): number { return queue.size; } /** * Returns how many more elements can be added before hitting capacity. * * @param queue - The target queue * @returns Number of available slots * * @example * ``` * if (remainingSpace(queue) < 10) { * console.warn('Queue nearly full, consider processing items'); * } * ``` */ export function remainingSpace(queue: Queue): number { return queue.capacity - queue.size; } ///////////////////////////// // Advanced Utility Functions // ///////////////////////////// /** * Empties the queue instantly using the `.length = 0` optimization[87][90]. * This immediately releases all object references for garbage collection, * making it much faster than dequeuing items one by one. * * Runs in O(1) constant time regardless of queue size. * * @param queue - The target queue * * @example * ``` * // Instead of: while (!isEmpty(queue)) dequeue(queue); // O(n) * clear(queue); // O(1) - much faster! * ``` */ export function clear(queue: Queue): void { // Fast array truncation - instantly releases references for GC[87][90] queue.items.length = 0; queue.items.length = queue.capacity; // restore original capacity // Reset pointers queue.head = 0; queue.tail = 0; queue.size = 0; } /** * Creates a new array containing all queue elements in order (front to back). * Useful for debugging, logging, or when you need array methods. * * Note: This is O(n) operation - use sparingly in performance-critical code. * * @param queue - The source queue * @returns New array with queue elements in FIFO order * * @example * ``` * const queueSnapshot = toArray(queue); * console.log('Current queue:', queueSnapshot.join(' -> ')); * * // Process without modifying original queue * const urgentItems = queueSnapshot.filter(item => item.priority === 'urgent'); * ``` */ export function toArray(queue: Queue): T[] { if (isEmpty(queue)) { return []; } const result = new Array(queue.size); let index = queue.head; for (let i = 0; i < queue.size; i++) { result[i] = queue.items[index]; index = advanceIndex(index, queue.capacity); } return result; } /** * Applies a function to each element in the queue without modifying it. * Elements are visited in FIFO order (front to back). * * @param queue - The target queue * @param callback - Function to call for each element * * @example * ``` * // Log all pending tasks * forEach(taskQueue, (task, index) => { * console.log(`Task ${index + 1}: ${task.description}`); * }); * ``` */ export function forEach( queue: Queue, callback: (item: T, index: number) => void, ): void { let index = queue.head; for (let i = 0; i < queue.size; i++) { callback(queue.items[index], i); index = advanceIndex(index, queue.capacity); } }