Skip to content

knotkit/deque

Queues elements at both ends in O(1) amortized time, over array and Float64Array ring buffers, with an optional fixed capacity that turns the queue into a sliding window

import {
function arrayDeque<A extends {} | null>(options?: DequeOptions<A>): Deque<A>

Create a

Deque

over a plain array ring buffer, for elements of any type except undefined. The type parameter excludes undefined, so arrayDeque<number | undefined>() fails to compile; store null, or a sentinel of your own, for a missing value.

@throws ― {DequeInvalidInputError} With code INVALID_CAPACITY when options.capacity is not Infinity or a positive safe integer no larger than DEQUE_MAX_CAPACITY (Infinity is accepted), INVALID_VALUE when options.items holds undefined, or MAX_CAPACITY_EXCEEDED when options.items holds more elements than the layout can store.

arrayDeque
} from 'knotkit/deque'
const
const frontier: Deque<string>
frontier
=
arrayDeque<string>(options?: DequeOptions<string>): Deque<string>

Create a

Deque

over a plain array ring buffer, for elements of any type except undefined. The type parameter excludes undefined, so arrayDeque<number | undefined>() fails to compile; store null, or a sentinel of your own, for a missing value.

@throws ― {DequeInvalidInputError} With code INVALID_CAPACITY when options.capacity is not Infinity or a positive safe integer no larger than DEQUE_MAX_CAPACITY (Infinity is accepted), INVALID_VALUE when options.items holds undefined, or MAX_CAPACITY_EXCEEDED when options.items holds more elements than the layout can store.

arrayDeque
({
DequeOptions<string>.items?: Iterable<string> | undefined

Elements to push at the back, in iteration order, as the deque is built. With

capacity

, only the last capacity of them remain, as if each had been pushed in turn.

items
: ['parse', 'layout'] })
const frontier: Deque<string>
frontier
.
Deque<string>.pushBack: (value: string) => string | undefined

Add an element at the back. O(1) amortized.

@returns ― The element evicted from the front when the deque was at capacity; otherwise undefined.

@throws ― {DequeInvalidInputError} With code INVALID_VALUE when the layout cannot store the value, or MAX_CAPACITY_EXCEEDED when growing would pass DEQUE_MAX_CAPACITY or the runtime refuses the allocation. The deque is unchanged after either.

pushBack
('render')
const frontier: Deque<string>
frontier
.
Deque<string>.popFront: () => string

Remove and return the element at the front. O(1).

@throws ― {DequeInvalidInputError} With code EMPTY when the deque is empty.

popFront
() // 'parse'
const frontier: Deque<string>
frontier
.
Deque<string>.popFront: () => string

Remove and return the element at the front. O(1).

@throws ― {DequeInvalidInputError} With code EMPTY when the deque is empty.

popFront
() // 'layout'
const frontier: Deque<string>
frontier
.
Deque<string>.popFront: () => string

Remove and return the element at the front. O(1).

@throws ― {DequeInvalidInputError} With code EMPTY when the deque is empty.

popFront
() // 'render'
deque.ts
import {
function float64ArrayDeque(options?: DequeOptions<number>): Deque<number>

Create a

Deque

of numbers over a Float64Array ring buffer: eight bytes per slot and no per-element allocation. NaN and -0 are stored as given.

@throws ― {DequeInvalidInputError} With code INVALID_CAPACITY when options.capacity is not Infinity or a positive safe integer no larger than DEQUE_MAX_CAPACITY (Infinity is accepted), INVALID_VALUE when options.items holds anything but numbers, or MAX_CAPACITY_EXCEEDED when options.items holds more elements than the runtime will allocate storage for.

float64ArrayDeque
} from 'knotkit/deque'
const
const window: Deque<number>
window
=
function float64ArrayDeque(options?: DequeOptions<number>): Deque<number>

Create a

Deque

of numbers over a Float64Array ring buffer: eight bytes per slot and no per-element allocation. NaN and -0 are stored as given.

@throws ― {DequeInvalidInputError} With code INVALID_CAPACITY when options.capacity is not Infinity or a positive safe integer no larger than DEQUE_MAX_CAPACITY (Infinity is accepted), INVALID_VALUE when options.items holds anything but numbers, or MAX_CAPACITY_EXCEEDED when options.items holds more elements than the runtime will allocate storage for.

float64ArrayDeque
({
DequeOptions<number>.capacity?: number | undefined

The most elements the deque holds. A push onto a full deque evicts the element at the opposite end and returns it, which makes a bounded deque a sliding window. Must be Infinity or a positive safe integer no larger than

DEQUE_MAX_CAPACITY

. Omit it, or pass Infinity, for a deque that grows without bound; that is the value

Deque.capacity

reports.

capacity
: 60 })
let
let sum: number
sum
= 0
function
function observe(value: number): number
observe
(
value: number
value
: number): number {
let sum: number
sum
+=
value: number
value
const
const evicted: number | undefined
evicted
=
const window: Deque<number>
window
.
Deque<number>.pushBack: (value: number) => number | undefined

Add an element at the back. O(1) amortized.

@returns ― The element evicted from the front when the deque was at capacity; otherwise undefined.

@throws ― {DequeInvalidInputError} With code INVALID_VALUE when the layout cannot store the value, or MAX_CAPACITY_EXCEEDED when growing would pass DEQUE_MAX_CAPACITY or the runtime refuses the allocation. The deque is unchanged after either.

pushBack
(
value: number
value
) // undefined until the window is full
if (
const evicted: number | undefined
evicted
!==
var undefined
undefined
)
let sum: number
sum
-=
const evicted: number
evicted
return
let sum: number
sum
/
const window: Deque<number>
window
.
Deque<number>.size: number

Number of elements held. O(1). The deque is empty when this is 0.

size
}
const readings = arrayDeque<number | null>({ capacity: 5 })
for (const reading of stream) readings.pushBack(reading ?? null) // reading: number | undefined
const last = [...readings].map((value) => value ?? undefined)
const second = recent.size >= 2 ? recent.at(-2) : undefined
const recent = arrayDeque({ items: ['a', 'b', 'c'] })
recent.at(0) // 'a'
recent.at(-1) // 'c'
for (const item of recent) console.log(item)
  • take items out in the order they arrived without Array.prototype.shift turning the loop quadratic
  • add and remove items at both ends of a sequence, such as a breadth-first and depth-first hybrid
  • keep only the last N values of a stream and learn which value just fell out, for a running sum or moving average
  • hold a long numeric buffer in eight bytes per value with no per-element allocation
  • read the k-th item from either end of a queue without removing anything
FactoryChoose whenCost
arrayDeque
kind array
any element is not a number, such as an object, a string, or nullone boxed slot per element and a slot write on every pop to release it; on the pinned 100,000-element first-in first-out bench it takes 2.6 times as long as float64-array
float64ArrayDeque
kind float64-array
every element is a number, including NaN and -0stores numbers only and rejects anything else with INVALID_VALUE; eight bytes per slot whether or not the value is an integer

Performance and benchmarks for this module

{"v":1,"box":[48.3056,94.1597,913.7333,437.3555],"x":{"s":"linear","lim":[0.145,20.855],"inv":false,"g":0,"t":"Reading number","tk":[[1,"1"],[5,"5"],[10,"10"],[15,"15"],[20,"20"]]},"y":{"s":"linear","lim":[11.28,28.72],"inv":false,"g":0,"tk":[[12,"12"],[15,"15"],[20,"20"],[25,"25"],[28,"28"]]},"ti":"A 5-reading mean flattens the 28 ms spike to at most 17.0 ms","a":[{"k":"line","c":"#fffff8","s":"x","d":[1,12,2,14,3,13,4,12,5,15,6,28,7,14,8,12,9,16,10,12,11,15,12,13,13,12,14,15,15,22,16,13,17,14,18,12,19,15,20,13],"p":[84.03,423.19,125.82,383.83,167.61,403.51,209.4,423.19,251.19,364.15,292.97,108.33,334.76,383.83,376.55,423.19,418.34,344.47,460.13,423.19,501.91,364.15,543.7,403.51,585.49,423.19,627.28,364.15,669.07,226.4,710.85,403.51,752.64,383.83,794.43,423.19,836.22,364.15,878,403.51]},{"k":"line","c":"#5b6b7c","s":"x","d":[1,12,2,14,3,13,4,12,5,15,6,28,7,14,8,12,9,16,10,12,11,15,12,13,13,12,14,15,15,22,16,13,17,14,18,12,19,15,20,13],"p":[84.03,423.19,125.82,383.83,167.61,403.51,209.4,423.19,251.19,364.15,292.97,108.33,334.76,383.83,376.55,423.19,418.34,344.47,460.13,423.19,501.91,364.15,543.7,403.51,585.49,423.19,627.28,364.15,669.07,226.4,710.85,403.51,752.64,383.83,794.43,423.19,836.22,364.15,878,403.51]},{"k":"line","c":"#fffff8","s":"x","d":[1,12,2,13,3,13,4,12.75,5,13.2,6,16.4,7,16.4,8,16.2,9,17,10,16.4,11,13.8,12,13.6,13,13.6,14,13.4,15,15.4,16,15,17,15.2,18,15.2,19,15.2,20,13.4],"p":[84.03,423.19,125.82,403.51,167.61,403.51,209.4,408.43,251.19,399.57,292.97,336.6,334.76,336.6,376.55,340.54,418.34,324.79,460.13,336.6,501.91,387.77,543.7,391.7,585.49,391.7,627.28,395.64,669.07,356.28,710.85,364.15,752.64,360.22,794.43,360.22,836.22,360.22,878,395.64]},{"k":"line","c":"#1d5fa6","s":"x","d":[1,12,2,13,3,13,4,12.75,5,13.2,6,16.4,7,16.4,8,16.2,9,17,10,16.4,11,13.8,12,13.6,13,13.6,14,13.4,15,15.4,16,15,17,15.2,18,15.2,19,15.2,20,13.4],"p":[84.03,423.19,125.82,403.51,167.61,403.51,209.4,408.43,251.19,399.57,292.97,336.6,334.76,336.6,376.55,340.54,418.34,324.79,460.13,336.6,501.91,387.77,543.7,391.7,585.49,391.7,627.28,395.64,669.07,356.28,710.85,364.15,752.64,360.22,794.43,360.22,836.22,360.22,878,395.64]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"fill","c":"#b97a00"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#b97a00"}],"lg":[]} 1 5 10 15 20 Reading number 12 15 20 25 28 Latency (ms) Readings Rolling mean 28 ms in the window A 5-reading mean flattens the 28 ms spike to at most 17.0 ms
{"v":1,"box":[48.3056,122.3921,465.7333,437.3555],"x":{"s":"linear","lim":[0.145,20.855],"inv":false,"g":0,"t":"Reading number","tk":[[1,"1"],[5,"5"],[10,"10"],[15,"15"],[20,"20"]]},"y":{"s":"linear","lim":[11.28,28.72],"inv":false,"g":0,"tk":[[12,"12"],[15,"15"],[20,"20"],[25,"25"],[28,"28"]]},"ti":"A 5-reading mean flattens the 28 ms spike\nto at most 17.0 ms","a":[{"k":"line","c":"#fffff8","s":"x","d":[1,12,2,14,3,13,4,12,5,15,6,28,7,14,8,12,9,16,10,12,11,15,12,13,13,12,14,15,15,22,16,13,17,14,18,12,19,15,20,13],"p":[65.54,424.35,85.69,388.23,105.85,406.29,126.01,424.35,146.16,370.17,166.32,135.4,186.47,388.23,206.63,424.35,226.79,352.11,246.94,424.35,267.1,370.17,287.25,406.29,307.41,424.35,327.56,370.17,347.72,243.75,367.88,406.29,388.03,388.23,408.19,424.35,428.34,370.17,448.5,406.29]},{"k":"line","c":"#5b6b7c","s":"x","d":[1,12,2,14,3,13,4,12,5,15,6,28,7,14,8,12,9,16,10,12,11,15,12,13,13,12,14,15,15,22,16,13,17,14,18,12,19,15,20,13],"p":[65.54,424.35,85.69,388.23,105.85,406.29,126.01,424.35,146.16,370.17,166.32,135.4,186.47,388.23,206.63,424.35,226.79,352.11,246.94,424.35,267.1,370.17,287.25,406.29,307.41,424.35,327.56,370.17,347.72,243.75,367.88,406.29,388.03,388.23,408.19,424.35,428.34,370.17,448.5,406.29]},{"k":"line","c":"#fffff8","s":"x","d":[1,12,2,13,3,13,4,12.75,5,13.2,6,16.4,7,16.4,8,16.2,9,17,10,16.4,11,13.8,12,13.6,13,13.6,14,13.4,15,15.4,16,15,17,15.2,18,15.2,19,15.2,20,13.4],"p":[65.54,424.35,85.69,406.29,105.85,406.29,126.01,410.81,146.16,402.68,166.32,344.89,186.47,344.89,206.63,348.5,226.79,334.05,246.94,344.89,267.1,391.84,287.25,395.46,307.41,395.46,327.56,399.07,347.72,362.95,367.88,370.17,388.03,366.56,408.19,366.56,428.34,366.56,448.5,399.07]},{"k":"line","c":"#1d5fa6","s":"x","d":[1,12,2,13,3,13,4,12.75,5,13.2,6,16.4,7,16.4,8,16.2,9,17,10,16.4,11,13.8,12,13.6,13,13.6,14,13.4,15,15.4,16,15,17,15.2,18,15.2,19,15.2,20,13.4],"p":[65.54,424.35,85.69,406.29,105.85,406.29,126.01,410.81,146.16,402.68,166.32,344.89,186.47,344.89,206.63,348.5,226.79,334.05,246.94,344.89,267.1,391.84,287.25,395.46,307.41,395.46,327.56,399.07,347.72,362.95,367.88,370.17,388.03,366.56,408.19,366.56,428.34,366.56,448.5,399.07]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"fill","c":"#b97a00"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#b97a00"}],"lg":[]} 1 5 10 15 20 Reading number 12 15 20 25 28 Latency (ms) Readings Rolling mean 28 ms in the window A 5-reading mean flattens the 28 ms spike to at most 17.0 ms
  • Mean over the last 5 readings: 13.40.
  • Both layouts retain the last 5 values: 13, 14, 12, 15, 13.
  • Each push returns the outgoing value once the window is full.

Hover or focus a chart for exact values. Each change reruns demo.ts against knotkit/deque in your browser; the defaults reproduce the README figure.

ExportReturnsDoes
arrayDequeDeque<A>Double-ended queue over a plain array ring buffer for any element type except undefined; an optional capacity evicts from the opposite end and returns the evicted element.
float64ArrayDequeDeque<number>Double-ended queue of numbers over a Float64Array ring buffer, eight bytes per slot; an optional capacity evicts from the opposite end and returns the evicted element.

Cost per member. Open a row for every operation.

arrayDeque 12 members
MemberCost
sizeO(1)
capacityO(1)
pushBackO(1) amortized
pushFrontO(1) amortized
popBackO(1)
popFrontO(1)
peekBackO(1)
peekFrontO(1)
atO(1)
clearO(1)
valuesO(1) per step, O(n) total
[Symbol.iterator]O(1) per step, O(n) total
float64ArrayDeque 12 members
MemberCost
sizeO(1)
capacityO(1)
pushBackO(1) amortized
pushFrontO(1) amortized
popBackO(1)
popFrontO(1)
peekBackO(1)
peekFrontO(1)
atO(1)
clearO(1)
valuesO(1) per step, O(n) total
[Symbol.iterator]O(1) per step, O(n) total

Every error this module throws is DequeInvalidInputError, with a code from a closed, exported list. Branch on the code; the message is for people.

EMPTY INVALID_CAPACITY INVALID_VALUE INVALID_INDEX MAX_CAPACITY_EXCEEDED MODIFIED_DURING_ITERATION
If you need to…Use instead
always take the smallest or largest item rather than the oldest or newestknotkit/heap
evict entries by key, recency of use, or total weightknotkit/cache
insert or remove items in the middle, or overwrite an item by indexArray with splice, or a linked list
a stack used at one end onlyArray push and pop, which are already O(1)
a bounded forward-only scan whose maximum size is known, such as a breadth-first walk over n verticesa pre-sized Int32Array or Float64Array with head and tail cursors, indexed by two integers that only move forward; it never wraps or grows, so a deque only adds cost

Measured by the suite in packages/deque/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone. Compare the recorded timings.

Prompt · knotkit/deque
Use knotkit/deque for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/deque'.

Exports:
- `arrayDeque` → `Deque<A>`: Double-ended queue over a plain array ring buffer for any element type except undefined; an optional capacity evicts from the opposite end and returns the evicted element.
- `float64ArrayDeque` → `Deque<number>`: Double-ended queue of numbers over a Float64Array ring buffer, eight bytes per slot; an optional capacity evicts from the opposite end and returns the evicted element.

Pick the layout by these rules:
- `arrayDeque` (kind 'array') when any element is not a number, such as an object, a string, or null
- `float64ArrayDeque` (kind 'float64-array') when every element is a number, including NaN and -0

Use something else when:
- always take the smallest or largest item rather than the oldest or newest → knotkit/heap
- evict entries by key, recency of use, or total weight → knotkit/cache
- insert or remove items in the middle, or overwrite an item by index → Array with splice, or a linked list
- a stack used at one end only → Array push and pop, which are already O(1)
- a bounded forward-only scan whose maximum size is known, such as a breadth-first walk over n vertices → a pre-sized Int32Array or Float64Array with head and tail cursors, indexed by two integers that only move forward; it never wraps or grows, so a deque only adds cost

Errors are DequeInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/deque.md
Types: node_modules/knotkit/deque/ and https://knotkit.jkomyno.dev/reference/knotkit/deque/