/** * data-structure-typed * * @author Pablo Zeng * @copyright Copyright (c) 2022 Pablo Zeng * @license MIT License */ import type { ElementCallback, LinearBaseOptions, QueueOptions } from '../../types'; import { SinglyLinkedList } from '../linked-list'; import { LinearBase } from '../base/linear-base'; /** * Array-backed queue with amortized O(1) enqueue/dequeue via an offset pointer and optional auto-compaction. * @remarks Time O(1), Space O(1) * @template E * @template R * 1. First In, First Out (FIFO): The core feature of a queue is its first in, first out nature. The element added to the queue first will be the one to be removed first. * 2. Operations: The main operations include enqueue (adding an element to the end of the queue) and dequeue (removing and returning the element at the front of the queue). Typically, there is also a peek operation (looking at the front element without removing it). * 3. Uses: Queues are commonly used to manage a series of tasks or elements that need to be processed in order. For example, managing task queues in a multi-threaded environment, or in algorithms for data structures like trees and graphs for breadth-first search. * 4. Task Scheduling: Managing the order of task execution in operating systems or applications. * 5. Data Buffering: Acting as a buffer for data packets in network communication. * 6. Breadth-First Search (BFS): In traversal algorithms for graphs and trees, queues store elements that are to be visited. * 7. Real-time Queuing: Like queuing systems in banks or supermarkets. * @example * // Queue as message broker for event processing * interface Message { * id: string; * type: 'email' | 'sms' | 'push'; * recipient: string; * content: string; * timestamp: Date; * } * * // Create a message queue for real-time event processing * const messageQueue = new Queue([ * { * id: 'msg-001', * type: 'email', * recipient: 'user@example.com', * content: 'Welcome!', * timestamp: new Date() * }, * { * id: 'msg-002', * type: 'sms', * recipient: '+1234567890', * content: 'OTP: 123456', * timestamp: new Date() * }, * { * id: 'msg-003', * type: 'push', * recipient: 'device-token-xyz', * content: 'New notification', * timestamp: new Date() * }, * { * id: 'msg-004', * type: 'email', * recipient: 'admin@example.com', * content: 'Daily report', * timestamp: new Date() * } * ]); * * // Process messages in FIFO order (first message first) * const processedMessages: string[] = []; * while (messageQueue.length > 0) { * const message = messageQueue.shift(); * if (message) { * processedMessages.push(`${message.type}:${message.recipient}`); * } * } * * // Verify messages were processed in order * console.log(processedMessages); // [ * // 'email:user@example.com', * // 'sms:+1234567890', * // 'push:device-token-xyz', * // 'email:admin@example.com' * // ]; * * // Queue should be empty after processing all messages * console.log(messageQueue.length); // 0; * @example * // Convert queue to array * const q = new Queue([10, 20, 30]); * console.log(q.toArray()); // [10, 20, 30]; */ export declare class Queue extends LinearBase { /** * Create a Queue and optionally bulk-insert elements. * @remarks Time O(N), Space O(N) * @param [elements] - Iterable of elements (or raw records if toElementFn is set). * @param [options] - Options such as toElementFn, maxLen, and autoCompactRatio. * @returns New Queue instance. */ constructor(elements?: Iterable | Iterable, options?: QueueOptions); protected _elements: E[]; /** * Get the underlying array buffer. * @remarks Time O(1), Space O(1) * @returns Backing array of elements. */ get elements(): E[]; protected _offset: number; /** * Get the current start offset into the array. * @remarks Time O(1), Space O(1) * @returns Zero-based offset. */ get offset(): number; protected _autoCompactRatio: number; /** * Get the compaction threshold (offset/size). * @remarks Time O(1), Space O(1) * @returns Auto-compaction ratio in (0,1]. */ get autoCompactRatio(): number; /** * Set the compaction threshold. * @remarks Time O(1), Space O(1) * @param value - New ratio; compacts when offset/size exceeds this value. * @returns void */ set autoCompactRatio(value: number); /** * Get the number of elements currently in the queue. * @remarks Time O(1), Space O(1) * @returns Current length. * @example * // Track queue length * const q = new Queue(); * console.log(q.length); // 0; * q.push(1); * q.push(2); * console.log(q.length); // 2; */ get length(): number; /** * Get the first element (front) without removing it. * @remarks Time O(1), Space O(1) * @returns Front element or undefined. * @example * // View the front element * const q = new Queue(['first', 'second', 'third']); * console.log(q.first); // 'first'; * console.log(q.length); // 3; */ get first(): E | undefined; /** * Peek at the front element without removing it (alias for `first`). * @remarks Time O(1), Space O(1) * @returns Front element or undefined. */ peek(): E | undefined; /** * Get the last element (back) without removing it. * @remarks Time O(1), Space O(1) * @returns Back element or undefined. */ get last(): E | undefined; /** * Create a queue from an array of elements. * @remarks Time O(N), Space O(N) * @template E * @param elements - Array of elements to enqueue in order. * @returns A new queue populated from the array. */ static fromArray(elements: E[]): Queue; /** * Check whether the queue is empty. * @remarks Time O(1), Space O(1) * @returns True if length is 0. * @example * // Queue for...of iteration and isEmpty check * const queue = new Queue(['A', 'B', 'C', 'D']); * * const elements: string[] = []; * for (const item of queue) { * elements.push(item); * } * * // Verify all elements are iterated in order * console.log(elements); // ['A', 'B', 'C', 'D']; * * // Process all elements * while (queue.length > 0) { * queue.shift(); * } * * console.log(queue.length); // 0; */ isEmpty(): boolean; /** * Enqueue one element at the back. * @remarks Time O(1), Space O(1) * @param element - Element to enqueue. * @returns True on success. * @example * // basic Queue creation and push operation * // Create a simple Queue with initial values * const queue = new Queue([1, 2, 3, 4, 5]); * * // Verify the queue maintains insertion order * console.log([...queue]); // [1, 2, 3, 4, 5]; * * // Check length * console.log(queue.length); // 5; */ push(element: E): boolean; /** * Enqueue many elements from an iterable. * @remarks Time O(N), Space O(1) * @param elements - Iterable of elements (or raw records if toElementFn is set). * @returns Array of per-element success flags. */ pushMany(elements: Iterable | Iterable): boolean[]; /** * Dequeue one element from the front (amortized via offset). * @remarks Time O(1) amortized, Space O(1) * @returns Removed element or undefined. * @example * // Queue shift and peek operations * const queue = new Queue([10, 20, 30, 40]); * * // Peek at the front element without removing it * console.log(queue.first); // 10; * * // Remove and get the first element (FIFO) * const first = queue.shift(); * console.log(first); // 10; * * // Verify remaining elements and length decreased * console.log([...queue]); // [20, 30, 40]; * console.log(queue.length); // 3; */ shift(): E | undefined; /** * Delete the first occurrence of a specific element. * @remarks Time O(N), Space O(1) * @param element - Element to remove (strict equality via Object.is). * @returns True if an element was removed. * @example * // Remove specific element * const q = new Queue([1, 2, 3, 2]); * q.delete(2); * console.log(q.length); // 3; */ delete(element: E): boolean; /** * Get the element at a given logical index. * @remarks Time O(1), Space O(1) * @param index - Zero-based index from the front. * @returns Element or undefined. * @example * // Access element by index * const q = new Queue(['a', 'b', 'c']); * console.log(q.at(0)); // 'a'; * console.log(q.at(2)); // 'c'; */ at(index: number): E | undefined; /** * Delete the element at a given index. * @remarks Time O(N), Space O(1) * @param index - Zero-based index from the front. * @returns Removed element or undefined. */ deleteAt(index: number): E | undefined; /** * Insert a new element at a given index. * @remarks Time O(N), Space O(1) * @param index - Zero-based index from the front. * @param newElement - Element to insert. * @returns True if inserted. */ addAt(index: number, newElement: E): boolean; /** * Replace the element at a given index. * @remarks Time O(1), Space O(1) * @param index - Zero-based index from the front. * @param newElement - New element to set. * @returns True if updated. */ setAt(index: number, newElement: E): boolean; /** * Delete the first element that satisfies a predicate. * @remarks Time O(N), Space O(N) * @param predicate - Function (value, index, queue) → boolean to decide deletion. * @returns True if a match was removed. */ deleteWhere(predicate: (value: E, index: number, queue: this) => boolean): boolean; /** * Reverse the queue in-place by compacting then reversing. * @remarks Time O(N), Space O(N) * @returns This queue. */ reverse(): this; /** * Remove all elements and reset offset. * @remarks Time O(1), Space O(1) * @returns void * @example * // Remove all elements * const q = new Queue([1, 2, 3]); * q.clear(); * console.log(q.length); // 0; */ clear(): void; /** * Compact storage by discarding consumed head elements. * @remarks Time O(N), Space O(N) * @returns True when compaction performed. * @example * // Reclaim unused memory * const q = new Queue([1, 2, 3, 4, 5]); * q.shift(); * q.shift(); * q.compact(); * console.log(q.length); // 3; */ compact(): boolean; /** * Remove and/or insert elements at a position (array-like). * @remarks Time O(N + M), Space O(M) * @param start - Start index (clamped to [0, length]). * @param [deleteCount] - Number of elements to remove (default 0). * @param [items] - Elements to insert after `start`. * @returns A new queue containing the removed elements (typed as `this`). */ splice(start: number, deleteCount?: number, ...items: E[]): this; /** * Deep clone this queue and its parameters. * @remarks Time O(N), Space O(N) * @returns A new queue with the same content and options. * @example * // Create independent copy * const q = new Queue([1, 2, 3]); * const copy = q.clone(); * copy.shift(); * console.log(q.length); // 3; * console.log(copy.length); // 2; */ clone(): this; /** * Filter elements into a new queue of the same class. * @remarks Time O(N), Space O(N) * @param predicate - Predicate (element, index, queue) → boolean to keep element. * @param [thisArg] - Value for `this` inside the predicate. * @returns A new queue with kept elements. * @example * // Filter elements * const q = new Queue([1, 2, 3, 4, 5]); * const evens = q.filter(x => x % 2 === 0); * console.log(evens.length); // 2; */ filter(predicate: ElementCallback, thisArg?: unknown): this; /** * Map each element to a new element in a possibly different-typed queue. * @remarks Time O(N), Space O(N) * @template EM * @template RM * @param callback - Mapping function (element, index, queue) → newElement. * @param [options] - Options for the output queue (e.g., toElementFn, maxLen, autoCompactRatio). * @param [thisArg] - Value for `this` inside the callback. * @returns A new Queue with mapped elements. * @example * // Transform elements * const q = new Queue([1, 2, 3]); * const doubled = q.map(x => x * 2); * console.log(doubled.toArray()); // [2, 4, 6]; */ map(callback: ElementCallback, options?: QueueOptions, thisArg?: unknown): Queue; /** * Map each element to a new value of the same type. * @remarks Time O(N), Space O(N) * @param callback - Mapping function (element, index, queue) → element. * @param [thisArg] - Value for `this` inside the callback. * @returns A new queue with mapped elements (same element type). */ mapSame(callback: ElementCallback, thisArg?: unknown): this; /** * (Protected) Set the internal auto-compaction ratio. * @remarks Time O(1), Space O(1) * @param value - New ratio to assign. * @returns void */ protected _setAutoCompactRatio(value: number): void; /** * (Protected) Iterate elements from front to back. * @remarks Time O(N), Space O(1) * @returns Iterator of E. */ protected _getIterator(): IterableIterator; /** * (Protected) Iterate elements from back to front. * @remarks Time O(N), Space O(1) * @returns Iterator of E. */ protected _getReverseIterator(): IterableIterator; /** * (Protected) Create an empty instance of the same concrete class. * @remarks Time O(1), Space O(1) * @param [options] - Options forwarded to the constructor. * @returns An empty like-kind queue instance. */ protected _createInstance(options?: LinearBaseOptions): this; /** * (Protected) Create a like-kind queue and seed it from an iterable. * @remarks Time O(N), Space O(N) * @template EM * @template RM * @param [elements] - Iterable used to seed the new queue. * @param [options] - Options forwarded to the constructor. * @returns A like-kind Queue instance. */ protected _createLike(elements?: Iterable | Iterable, options?: QueueOptions): Queue; } /** * Queue implemented over a singly linked list; preserves head/tail operations with linear scans for queries. * @remarks Time O(1), Space O(1) * @template E * @template R * @example examples will be generated by unit test */ export declare class LinkedListQueue extends SinglyLinkedList { /** * Deep clone this linked-list-based queue. * @remarks Time O(N), Space O(N) * @returns A new queue with the same sequence of elements. */ clone(): this; }