Class Queue<E, R>

Array-backed queue with amortized O(1) enqueue/dequeue via an offset pointer and optional auto-compaction.

Time O(1), Space O(1)

// Sliding Window using Queue
const nums = [2, 3, 4, 1, 5];
const k = 2;
const queue = new Queue<number>();

let maxSum = 0;
let currentSum = 0;

nums.forEach(num => {
queue.push(num);
currentSum += num;

if (queue.length > k) {
currentSum -= queue.shift()!;
}

if (queue.length === k) {
maxSum = Math.max(maxSum, currentSum);
}
});

console.log(maxSum); // 7
// Breadth-First Search (BFS) using Queue
const graph: { [key in number]: number[] } = {
1: [2, 3],
2: [4, 5],
3: [],
4: [],
5: []
};

const queue = new Queue<number>();
const visited: number[] = [];

queue.push(1);

while (!queue.isEmpty()) {
const node = queue.shift()!;
if (!visited.includes(node)) {
visited.push(node);
graph[node].forEach(neighbor => queue.push(neighbor));
}
}

console.log(visited); // [1, 2, 3, 4, 5]

Type Parameters

  • E = any
  • R = any
    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.

Hierarchy

  • LinearBase<E, R>
    • Queue

Constructors

  • Create a Queue and optionally bulk-insert elements.

    Type Parameters

    • E = any
    • R = any

    Parameters

    • Optionalelements: Iterable<E, any, any> | Iterable<R, any, any> = []

      Iterable of elements (or raw records if toElementFn is set).

    • Optionaloptions: QueueOptions<E, R>

      Options such as toElementFn, maxLen, and autoCompactRatio.

    Returns Queue<E, R>

    New Queue instance.

    Time O(N), Space O(N)

Properties

_toElementFn?: ((rawElement: R) => E)

The converter used to transform a raw element (R) into a public element (E).

Time O(1), Space O(1).

Accessors

  • get autoCompactRatio(): number
  • Get the compaction threshold (offset/size).

    Returns number

    Auto-compaction ratio in (0,1].

    Time O(1), Space O(1)

  • set autoCompactRatio(value): void
  • Set the compaction threshold.

    Parameters

    • value: number

      New ratio; compacts when offset/size exceeds this value.

    Returns void

    void

    Time O(1), Space O(1)

  • get first(): undefined | E
  • Get the first element (front) without removing it.

    Returns undefined | E

    Front element or undefined.

    Time O(1), Space O(1)

  • get last(): undefined | E
  • Get the last element (back) without removing it.

    Returns undefined | E

    Back element or undefined.

    Time O(1), Space O(1)

  • get length(): number
  • Get the number of elements currently in the queue.

    Returns number

    Current length.

    Time O(1), Space O(1)

  • get maxLen(): number
  • Upper bound for length (if positive), or -1 when unbounded.

    Returns number

    Maximum allowed length.

    Time O(1), Space O(1)

  • get offset(): number
  • Get the current start offset into the array.

    Returns number

    Zero-based offset.

    Time O(1), Space O(1)

  • get toElementFn(): undefined | ((rawElement: R) => E)
  • Exposes the current toElementFn, if configured.

    Returns undefined | ((rawElement: R) => E)

    The converter function or undefined when not set.

    Time O(1), Space O(1).

Methods

  • (Protected) Create an empty instance of the same concrete class.

    Parameters

    • Optionaloptions: LinearBaseOptions<E, R>

      Options forwarded to the constructor.

    Returns this

    An empty like-kind queue instance.

    Time O(1), Space O(1)

  • (Protected) Create a like-kind queue and seed it from an iterable.

    Type Parameters

    • EM = E
    • RM = R

    Parameters

    • Optionalelements: Iterable<EM, any, any> | Iterable<RM, any, any> = []

      Iterable used to seed the new queue.

    • Optionaloptions: QueueOptions<EM, RM>

      Options forwarded to the constructor.

    Returns Queue<EM, RM>

    A like-kind Queue instance.

    Time O(N), Space O(N)

  • (Protected) Iterate elements from front to back.

    Returns IterableIterator<E, any, any>

    Iterator of E.

    Time O(N), Space O(1)

  • (Protected) Iterate elements from back to front.

    Returns IterableIterator<E, any, any>

    Iterator of E.

    Time O(N), Space O(1)

  • (Protected) Set the internal auto-compaction ratio.

    Parameters

    • value: number

      New ratio to assign.

    Returns void

    void

    Time O(1), Space O(1)

  • Returns an iterator over the structure's elements.

    Parameters

    • Rest...args: unknown[]

      Optional iterator arguments forwarded to the internal iterator.

    Returns IterableIterator<E, any, any>

    An IterableIterator<E> that yields the elements in traversal order.

    Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.

  • Insert a new element at a given index.

    Parameters

    • index: number

      Zero-based index from the front.

    • newElement: E

      Element to insert.

    Returns boolean

    True if inserted.

    Time O(N), Space O(1)

  • Get the element at a given logical index.

    Parameters

    • index: number

      Zero-based index from the front.

    Returns undefined | E

    Element or undefined.

    Time O(1), Space O(1)

  • Deep clone this queue and its parameters.

    Returns this

    A new queue with the same content and options.

    Time O(N), Space O(N)

  • Compact storage by discarding consumed head elements.

    Returns boolean

    True when compaction performed.

    Time O(N), Space O(N)

  • Concatenate multiple containers of the same species.

    Parameters

    • Rest...items: Queue<E, R>[]

      Other lists to append.

    Returns this

    New container with combined elements (this type).

    Time O(sum(length)), Space O(sum(length))

  • Delete the first occurrence of a specific element.

    Parameters

    • element: E

      Element to remove (strict equality via Object.is).

    Returns boolean

    True if an element was removed.

    Time O(N), Space O(1)

  • Delete the element at a given index.

    Parameters

    • index: number

      Zero-based index from the front.

    Returns undefined | E

    Removed element or undefined.

    Time O(N), Space O(1)

  • Tests whether all elements satisfy the predicate.

    Parameters

    • predicate: ElementCallback<E, R, boolean>

      Function invoked for each element with signature (value, index, self).

    • OptionalthisArg: unknown

      Optional this binding for the predicate.

    Returns boolean

    true if every element passes; otherwise false.

    Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).

  • Fill a range with a value.

    Parameters

    • value: E

      Value to set.

    • start: number = 0

      Inclusive start.

    • end: number = ...

      Exclusive end.

    Returns this

    This list.

    Time O(n), Space O(1)

  • Filter elements into a new queue of the same class.

    Parameters

    • predicate: ElementCallback<E, R, boolean>

      Predicate (element, index, queue) → boolean to keep element.

    • OptionalthisArg: unknown

      Value for this inside the predicate.

    Returns this

    A new queue with kept elements.

    Time O(N), Space O(N)

  • Finds the first element that satisfies the predicate and returns it.

    Finds the first element of type S (a subtype of E) that satisfies the predicate and returns it.

    Type Parameters

    • S

    Parameters

    • predicate: ElementCallback<E, R, S>

      Type-guard predicate: (value, index, self) => value is S.

    • OptionalthisArg: unknown

      Optional this binding for the predicate.

    Returns undefined | S

    The matched element typed as S, or undefined if not found.

    Time O(n) in the worst case; may exit early on the first match. Space O(1).

  • Find the first index matching a predicate.

    Parameters

    • predicate: ElementCallback<E, R, boolean>

      (element, index, self) => boolean.

    • OptionalthisArg: any

      Optional this for callback.

    Returns number

    Index or -1.

    Time O(n), Space O(1)

  • Invokes a callback for each element in iteration order.

    Parameters

    • callbackfn: ElementCallback<E, R, void>

      Function invoked per element with signature (value, index, self).

    • OptionalthisArg: unknown

      Optional this binding for the callback.

    Returns void

    void.

    Time O(n), Space O(1).

  • Checks whether a strictly-equal element exists in the structure.

    Parameters

    • element: E

      The element to test with === equality.

    Returns boolean

    true if an equal element is found; otherwise false.

    Time O(n) in the worst case. Space O(1).

  • First index of a value from the left.

    Parameters

    • searchElement: E

      Value to match.

    • fromIndex: number = 0

      Start position (supports negative index).

    Returns number

    Index or -1 if not found.

    Time O(n), Space O(1)

  • Check whether the queue is empty.

    Returns boolean

    True if length is 0.

    Time O(1), Space O(1)

  • Join all elements into a string.

    Parameters

    • separator: string = ','

      Separator string.

    Returns string

    Concatenated string.

    Time O(n), Space O(n)

  • Last index of a value from the right.

    Parameters

    • searchElement: E

      Value to match.

    • fromIndex: number = ...

      Start position (supports negative index).

    Returns number

    Index or -1 if not found.

    Time O(n), Space O(1)

  • Map each element to a new element in a possibly different-typed queue.

    Type Parameters

    • EM
    • RM

    Parameters

    • callback: ElementCallback<E, R, EM>

      Mapping function (element, index, queue) → newElement.

    • Optionaloptions: QueueOptions<EM, RM>

      Options for the output queue (e.g., toElementFn, maxLen, autoCompactRatio).

    • OptionalthisArg: unknown

      Value for this inside the callback.

    Returns Queue<EM, RM>

    A new Queue with mapped elements.

    Time O(N), Space O(N)

  • Map each element to a new value of the same type.

    Parameters

    • callback: ElementCallback<E, R, E>

      Mapping function (element, index, queue) → element.

    • OptionalthisArg: unknown

      Value for this inside the callback.

    Returns this

    A new queue with mapped elements (same element type).

    Time O(N), Space O(N)

  • Prints toVisual() to the console. Intended for quick debugging.

    Returns void

    void.

    Time O(n) due to materialization, Space O(n) for the intermediate representation.

  • Enqueue one element at the back.

    Parameters

    • element: E

      Element to enqueue.

    Returns boolean

    True on success.

    Time O(1), Space O(1)

  • Enqueue many elements from an iterable.

    Parameters

    • elements: Iterable<E, any, any> | Iterable<R, any, any>

      Iterable of elements (or raw records if toElementFn is set).

    Returns boolean[]

    Array of per-element success flags.

    Time O(N), Space O(1)

  • Right-to-left reduction over elements.

    Type Parameters

    • U

    Parameters

    • callbackfn: ReduceLinearCallback<E, U>

      (acc, element, index, self) => acc.

    • initialValue: U

      Initial accumulator (optional generic overloads supported).

    Returns U

    Final accumulator.

    Time O(n), Space O(1)

  • Reverse the queue in-place by compacting then reversing.

    Returns this

    This queue.

    Time O(N), Space O(N)

  • Replace the element at a given index.

    Parameters

    • index: number

      Zero-based index from the front.

    • newElement: E

      New element to set.

    Returns boolean

    True if updated.

    Time O(1), Space O(1)

  • Dequeue one element from the front (amortized via offset).

    Returns undefined | E

    Removed element or undefined.

    Time O(1) amortized, Space O(1)

  • Create a shallow copy of a subrange.

    Parameters

    • start: number = 0

      Inclusive start (supports negative index).

    • end: number = ...

      Exclusive end (supports negative index).

    Returns this

    New list with the range (this type).

    Time O(n), Space O(n)

  • Tests whether at least one element satisfies the predicate.

    Parameters

    • predicate: ElementCallback<E, R, boolean>

      Function invoked for each element with signature (value, index, self).

    • OptionalthisArg: unknown

      Optional this binding for the predicate.

    Returns boolean

    true if any element passes; otherwise false.

    Time O(n) in the worst case; may exit early on first success. Space O(1).

  • In-place stable order via array sort semantics.

    Parameters

    • OptionalcompareFn: ((a: E, b: E) => number)

      Comparator (a, b) => number.

        • (a, b): number
        • Parameters

          Returns number

    Returns this

    This container.

    Time O(n log n), Space O(n) (materializes to array temporarily)

  • Remove and/or insert elements at a position (array-like).

    Parameters

    • start: number

      Start index (clamped to [0, length]).

    • OptionaldeleteCount: number = 0

      Number of elements to remove (default 0).

    • Optional Rest...items: E[]

      Elements to insert after start.

    Returns this

    A new queue containing the removed elements (typed as this).

    Time O(N + M), Space O(M)

  • Snapshot elements into a reversed array.

    Returns E[]

    New reversed array.

    Time O(n), Space O(n)

  • Returns a representation of the structure suitable for quick visualization. Defaults to an array of elements; subclasses may override to provide richer visuals.

    Returns E[]

    A visual representation (array by default).

    Time O(n), Space O(n).

  • Returns an iterator over the values (alias of the default iterator).

    Returns IterableIterator<E, any, any>

    An IterableIterator<E> over all elements.

    Creating the iterator is O(1); full iteration is Time O(n), Space O(1).

  • Create a queue from an array of elements.

    Type Parameters

    • E

    Parameters

    • elements: E[]

      Array of elements to enqueue in order.

    Returns Queue<E, any>

    A new queue populated from the array.

    Time O(N), Space O(N)