# 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

## Use

```ts
import { arrayDeque } from 'knotkit/deque'

const frontier = arrayDeque({ items: ['parse', 'layout'] })
frontier.pushBack('render')
frontier.popFront() // 'parse'
frontier.popFront() // 'layout'
frontier.popFront() // 'render'
```

```ts
import { float64ArrayDeque } from 'knotkit/deque'

const window = float64ArrayDeque({ capacity: 60 })
let sum = 0

function observe(value: number): number {
  sum += value
  const evicted = window.pushBack(value) // undefined until the window is full
  if (evicted !== undefined) sum -= evicted
  return sum / window.size
}
```

```ts
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)
```

```ts
const second = recent.size >= 2 ? recent.at(-2) : undefined
```

```ts
const recent = arrayDeque({ items: ['a', 'b', 'c'] })

recent.at(0) // 'a'
recent.at(-1) // 'c'
for (const item of recent) console.log(item)
```

## What it solves

* 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

## Choose a layout

| Factory                                 | Choose when                                                       | Cost                                                                                                                                                                       |
| --------------------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `arrayDeque`kind `array`                | any element is not a number, such as an object, a string, or null | one 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 -0                   | stores 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](https://github.com/jkomyno/knotkit/blob/main/packages/deque/README.md#performance)

## Try it

Window (readings)55Reset

* 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`](https://github.com/jkomyno/knotkit/blob/main/packages/deque/demo.ts) against `knotkit/deque` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                       | Returns         | Does                                                                                                                                                                        |
| ---------------------------------------------------------------------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`arrayDeque`](/reference/knotkit/deque/functions/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`](/reference/knotkit/deque/functions/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.     |

Cost per member. Open a row for every operation.

`arrayDeque` 12 members

| Member              | Cost                      |
| ------------------- | ------------------------- |
| `size`              | O(1)                      |
| `capacity`          | O(1)                      |
| `pushBack`          | O(1) amortized            |
| `pushFront`         | O(1) amortized            |
| `popBack`           | O(1)                      |
| `popFront`          | O(1)                      |
| `peekBack`          | O(1)                      |
| `peekFront`         | O(1)                      |
| `at`                | O(1)                      |
| `clear`             | O(1)                      |
| `values`            | O(1) per step, O(n) total |
| `[Symbol.iterator]` | O(1) per step, O(n) total |

`float64ArrayDeque` 12 members

| Member              | Cost                      |
| ------------------- | ------------------------- |
| `size`              | O(1)                      |
| `capacity`          | O(1)                      |
| `pushBack`          | O(1) amortized            |
| `pushFront`         | O(1) amortized            |
| `popBack`           | O(1)                      |
| `popFront`          | O(1)                      |
| `peekBack`          | O(1)                      |
| `peekFront`         | O(1)                      |
| `at`                | O(1)                      |
| `clear`             | O(1)                      |
| `values`            | O(1) per step, O(n) total |
| `[Symbol.iterator]` | O(1) per step, O(n) total |

## Errors

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`

## When not to use it

| If you need to…                                                                                       | Use instead                                                                                                                                                           |
| ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| always take the smallest or largest item rather than the oldest or newest                             | [`knotkit/heap`](/modules/heap/)                                                                                                                                      |
| evict entries by key, recency of use, or total weight                                                 | [`knotkit/cache`](/modules/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 |

## Performance

Measured by the suite in [`packages/deque/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/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](/benchmarks/#deque).

## Prompt an agent

Prompt · knotkit/dequeCopy prompt

```
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/
```

## See also

* [API reference](/reference/knotkit/deque/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/deque/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/deque/knotkit.capability.json)suggest a change to the source record
