MCPcopy Create free account
hub / github.com/denoland/std / Deque

Class Deque

data_structures/deque.ts:80–865  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

78 * @typeParam T The type of the values stored in the deque.
79 */
80export class Deque<T> implements Iterable<T>, ReadonlyDeque<T> {
81 #buffer: (T | undefined)[];
82 #head: number;
83 #length: number;
84 /** Always `#capacity - 1`. Used to wrap indices via `& #mask`. */
85 #mask: number;
86
87 get #capacity(): number {
88 return this.#mask + 1;
89 }
90
91 /**
92 * Creates an empty deque, optionally populated from an iterable.
93 *
94 * @example Creating an empty deque
95 * ```ts
96 * import { Deque } from "@std/data-structures/deque";
97 * import { assertEquals } from "@std/assert";
98 *
99 * const deque = new Deque<number>();
100 * assertEquals(deque.length, 0);
101 * ```
102 *
103 * @example Creating a deque from an iterable
104 * ```ts
105 * import { Deque } from "@std/data-structures/deque";
106 * import { assertEquals } from "@std/assert";
107 *
108 * const deque = new Deque([1, 2, 3]);
109 * assertEquals([...deque], [1, 2, 3]);
110 * ```
111 *
112 * @param source An optional iterable to populate the deque.
113 */
114 constructor(source?: Iterable<T>) {
115 if (source === undefined || source === null) {
116 this.#buffer = new Array(MIN_CAPACITY);
117 this.#head = 0;
118 this.#length = 0;
119 this.#mask = MIN_CAPACITY - 1;
120 return;
121 }
122 if (source instanceof Deque) {
123 const capacity = nextPowerOfTwo(source.#length);
124 this.#buffer = Deque.#copyBuffer(source, capacity);
125 this.#head = 0;
126 this.#length = source.#length;
127 this.#mask = capacity - 1;
128 return;
129 }
130 if (
131 typeof source !== "object" && typeof source !== "string" ||
132 !(Symbol.iterator in Object(source))
133 ) {
134 throw new TypeError(
135 "Cannot construct a Deque: the 'source' parameter is not iterable, did you mean to call Deque.from?",
136 );
137 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected