Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/observables. A spec-faithful yet ergonomic TC39-inspired Observable library with detailed ty
Something went wrong. Try again.
observables queue.ts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315/** * 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<T> { /** 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<string>(50); // for messages * const numberQueue = createQueue<number>(); // uses default capacity * ``` */export function createQueue<T>(capacity: number = 1000): Queue<T> { return { items: new Array<T>(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<T>(queue: Queue<T>, 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<T>(queue: Queue<T>): 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<T>(queue: Queue<T>): 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<T>(queue: Queue<T>): 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<T>(queue: Queue<T>): 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<T>(queue: Queue<T>): 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<T>(queue: Queue<T>): 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<T>(queue: Queue<T>): 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<T>(queue: Queue<T>): T[] { if (isEmpty(queue)) { return []; }
const result = new Array<T>(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<T>( queue: Queue<T>, 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); }}