Class Deque<E, R>

Deque implemented with circular buckets allowing O(1) amortized push/pop at both ends.

Time O(1), Space O(1)

// basic Deque creation and push/pop operations
// Create a simple Deque with initial values
const deque = new Deque([1, 2, 3, 4, 5]);

// Verify the deque maintains insertion order
console.log([...deque]); // [1, 2, 3, 4, 5];

// Check length
console.log(deque.length); // 5;

// Push to the end
deque.push(6);
console.log(deque.length); // 6;

// Pop from the end
const last = deque.pop();
console.log(last); // 6;
// Deque shift and unshift operations
const deque = new Deque<number>([20, 30, 40]);

// Unshift adds to the front
deque.unshift(10);
console.log([...deque]); // [10, 20, 30, 40];

// Shift removes from the front (O(1) complexity!)
const first = deque.shift();
console.log(first); // 10;

// Verify remaining elements
console.log([...deque]); // [20, 30, 40];
console.log(deque.length); // 3;
// Deque peek at both ends
const deque = new Deque<number>([10, 20, 30, 40, 50]);

// Get first element without removing
const first = deque.at(0);
console.log(first); // 10;

// Get last element without removing
const last = deque.at(deque.length - 1);
console.log(last); // 50;

// Length unchanged
console.log(deque.length); // 5;
// Deque for...of iteration and reverse
const deque = new Deque<string>(['A', 'B', 'C', 'D']);

// Iterate forward
const forward: string[] = [];
for (const item of deque) {
forward.push(item);
}
console.log(forward); // ['A', 'B', 'C', 'D'];

// Reverse the deque
deque.reverse();
const backward: string[] = [];
for (const item of deque) {
backward.push(item);
}
console.log(backward); // ['D', 'C', 'B', 'A'];
// Deque as sliding window for stream processing
interface DataPoint {
timestamp: number;
value: number;
sensor: string;
}

// Create a deque-based sliding window for real-time data aggregation
const windowSize = 3;
const dataWindow = new Deque<DataPoint>();

// Simulate incoming sensor data stream
const incomingData: DataPoint[] = [
{ timestamp: 1000, value: 25.5, sensor: 'temp-01' },
{ timestamp: 1100, value: 26.2, sensor: 'temp-01' },
{ timestamp: 1200, value: 25.8, sensor: 'temp-01' },
{ timestamp: 1300, value: 27.1, sensor: 'temp-01' },
{ timestamp: 1400, value: 26.9, sensor: 'temp-01' }
];

const windowResults: Array<{ avgValue: number; windowSize: number }> = [];

for (const dataPoint of incomingData) {
// Add new data to the end
dataWindow.push(dataPoint);

// Remove oldest data when window exceeds size (O(1) from front)
if (dataWindow.length > windowSize) {
dataWindow.shift();
}

// Calculate average of current window
let sum = 0;
for (const point of dataWindow) {
sum += point.value;
}
const avg = sum / dataWindow.length;

windowResults.push({
avgValue: Math.round(avg * 10) / 10,
windowSize: dataWindow.length
});
}

// Verify sliding window behavior
console.log(windowResults.length); // 5;
console.log(windowResults[0].windowSize); // 1; // First window has 1 element
console.log(windowResults[2].windowSize); // 3; // Windows are at max size from 3rd onwards
console.log(windowResults[4].windowSize); // 3; // Last window still has 3 elements
console.log(dataWindow.length); // 3;

Type Parameters

  • E = any
  • R = any
    1. Operations at Both Ends: Supports adding and removing elements at both the front and back of the queue. This allows it to be used as a stack (last in, first out) and a queue (first in, first out).
    2. Efficient Random Access: Being based on an array, it offers fast random access capability, allowing constant time access to any element.
    3. Continuous Memory Allocation: Since it is based on an array, all elements are stored contiguously in memory, which can bring cache friendliness and efficient memory access.
    4. Efficiency: Adding and removing elements at both ends of a deque is usually very fast. However, when the dynamic array needs to expand, it may involve copying the entire array to a larger one, and this operation has a time complexity of O(n).
    5. Performance jitter: Deque may experience performance jitter, but DoublyLinkedList will not

Hierarchy

  • LinearBase<E, R>
    • Deque

Constructors

  • Create a Deque and optionally bulk-insert elements.

    Type Parameters

    • E = any
    • R = any

    Parameters

    • Optionalelements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R> = []

      Iterable (or iterable-like) of elements/records to insert.

    • Optionaloptions: DequeOptions<E, R>

      Options such as bucketSize, toElementFn, and maxLen.

    Returns Deque<E, R>

    New Deque 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 bucketFirst(): number
  • Get the index of the first bucket in use.

    Returns number

    Zero-based bucket index.

    Time O(1), Space O(1)

  • get bucketLast(): number
  • Get the index of the last bucket in use.

    Returns number

    Zero-based bucket index.

    Time O(1), Space O(1)

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

    Returns undefined | E

    First element or undefined.

    Time O(1), Space O(1)

  • get firstInBucket(): number
  • Get the index inside the first bucket.

    Returns number

    Zero-based index within the first bucket.

    Time O(1), Space O(1)

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

    Returns undefined | E

    Last element or undefined.

    Time O(1), Space O(1)

  • get lastInBucket(): number
  • Get the index inside the last bucket.

    Returns number

    Zero-based index within the last bucket.

    Time O(1), Space O(1)

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

    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 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 deque instance.

    Time O(1), Space O(1)

  • (Protected) Create a like-kind deque seeded by elements.

    Type Parameters

    • T = E
    • RR = R

    Parameters

    • Optionalelements: IterableWithSizeOrLength<T> | IterableWithSizeOrLength<RR> = []

      Iterable used to seed the new deque.

    • Optionaloptions: DequeOptions<T, RR>

      Options forwarded to the constructor.

    Returns any

    A like-kind Deque instance.

    Time O(N), Space O(N)

  • (Protected) Translate a logical position to bucket/offset.

    Parameters

    • pos: number

      Zero-based position.

    Returns {
        bucketIndex: number;
        indexInBucket: number;
    }

    An object containing bucketIndex and indexInBucket.

    • bucketIndex: number
    • indexInBucket: number

    Time O(1), Space O(1)

  • (Protected) Iterate elements from front to back.

    Returns IterableIterator<E, any, any>

    Iterator of elements.

    Time O(N), Space O(1)

  • (Protected) Iterate elements from back to front.

    Returns IterableIterator<E, any, any>

    Iterator of elements.

    Time O(N), Space O(1)

  • (Protected) Reallocate buckets to make room near the ends.

    Parameters

    • OptionalneedBucketNum: number

      How many extra buckets to add; defaults to half of current.

    Returns void

    void

    Time O(N), Space O(N)

  • (Protected) Set the internal bucket size.

    Parameters

    • size: number

      Bucket capacity 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 repeated copies of an element at a position.

    Parameters

    • pos: number

      Zero-based position from the front.

    • element: E

      Element to insert.

    • Optionalnum: number = 1

      Number of times to insert (default 1).

    Returns boolean

    True if inserted.

    Time O(N), Space O(1)

  • Get the element at a given position.

    Parameters

    • pos: number

      Zero-based position from the front.

    Returns undefined | E

    Element or undefined.

    Time O(1), Space O(1)

  • Remove all elements and reset structure.

    Returns void

    void

    Time O(1), Space O(1)

  • Deep clone this deque, preserving options.

    Returns this

    A new deque with the same content and options.

    Time O(N), Space O(N)

  • Concatenate multiple containers of the same species.

    Parameters

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

      Other lists to append.

    Returns this

    New container with combined elements (this type).

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

  • Cut the deque to keep items up to index; optionally mutate in-place.

    Parameters

    • pos: number

      Last index to keep.

    • OptionalisCutSelf: boolean = false

      When true, mutate this deque; otherwise return a new deque.

    Returns Deque<E, any>

    This deque if in-place; otherwise a new deque of the prefix.

    Time O(N), Space O(1)

  • Cut the deque to keep items from index onward; optionally mutate in-place.

    Parameters

    • pos: number

      First index to keep.

    • OptionalisCutSelf: boolean = false

      When true, mutate this deque; otherwise return a new deque.

    Returns Deque<E, any>

    This deque if in-place; otherwise a new deque of the suffix.

    Time O(N), Space O(1)

  • Delete the first occurrence of a value.

    Parameters

    • element: E

      Element to remove (using the configured equality).

    Returns boolean

    True if an element was removed.

    Time O(N), Space O(1)

  • Delete the element at a given position.

    Parameters

    • pos: number

      Zero-based position from the front.

    Returns undefined | E

    Removed element or undefined.

    Time O(N), Space O(1)

  • Delete the first element matching a predicate.

    Parameters

    • predicate: ((value: E, index: number, deque: this) => boolean)

      Function (value, index, deque) → boolean.

        • (value, index, deque): boolean
        • Parameters

          • value: E
          • index: number
          • deque: this

          Returns boolean

    Returns boolean

    True if a match was removed.

    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 deque of the same class.

    Parameters

    • predicate: ElementCallback<E, R, boolean>

      Predicate (value, index, deque) → boolean to keep element.

    • OptionalthisArg: any

      Value for this inside the predicate.

    Returns this

    A new deque 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 deque 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 elements into a new deque (possibly different element type).

    Type Parameters

    • EM
    • RM

    Parameters

    • callback: ElementCallback<E, R, EM>

      Mapping function (value, index, deque) → newElement.

    • Optionaloptions: IterableElementBaseOptions<EM, RM>

      Options for the output deque (e.g., bucketSize, toElementFn, maxLen).

    • OptionalthisArg: any

      Value for this inside the callback.

    Returns Deque<EM, RM>

    A new Deque with mapped elements.

    Time O(N), Space O(N)

  • Map elements into a new deque of the same element type.

    Parameters

    • callback: ElementCallback<E, R, E>

      Mapping function (value, index, deque) → newValue.

    • OptionalthisArg: any

      Value for this inside the callback.

    Returns this

    A new deque with mapped values.

    Time O(N), Space O(N)

  • Remove and return the last element.

    Returns undefined | E

    Removed element or undefined.

    Time O(1), Space O(1)

  • 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.

  • Append one element at the back.

    Parameters

    • element: E

      Element to append.

    Returns boolean

    True when appended.

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

  • Append a sequence of elements.

    Parameters

    • elements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R>

      Iterable (or iterable-like) of elements/records.

    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 deque by reversing buckets and pointers.

    Returns this

    This deque.

    Time O(N), Space O(N)

  • Replace the element at a given position.

    Parameters

    • pos: number

      Zero-based position from the front.

    • element: E

      New element value.

    Returns boolean

    True if updated.

    Time O(1), Space O(1)

  • Set the equality comparator used by delete operations.

    Parameters

    • equals: ((a: E, b: E) => boolean)

      Equality predicate (a, b) → boolean.

        • (a, b): boolean
        • Parameters

          Returns boolean

    Returns this

    This deque.

    Time O(1), Space O(1)

  • Remove and return the first element.

    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 behavior).

    Parameters

    • start: number

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

    • OptionaldeleteCount: number = ...

      Number of elements to remove (default: length - start).

    • Optional Rest...items: E[]

      Elements to insert after start.

    Returns this

    A new deque 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).

  • Prepend one element at the front.

    Parameters

    • element: E

      Element to prepend.

    Returns boolean

    True when prepended.

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

  • Prepend a sequence of elements.

    Parameters

    • Optionalelements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R> = []

      Iterable (or iterable-like) of elements/records.

    Returns boolean[]

    Array of per-element success flags.

    Time O(N), Space O(1)

  • 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 Deque from an array of elements.

    Type Parameters

    • E
    • R = any

    Parameters

    • this: Object

      Constructor (subclass) to instantiate.

    • data: E[]

      Array of elements to insert in order.

    • Optionaloptions: DequeOptions<E, R>

      Options forwarded to the constructor.

    Returns any

    A new Deque populated from the array.

    Time O(N), Space O(N)