@bodil/core 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/async/abortable-promise.d.ts +71 -0
  2. package/dist/async/abortable-promise.js +204 -0
  3. package/dist/async/abortable-promise.js.map +1 -0
  4. package/dist/async/abortable-promise.test.d.ts +1 -0
  5. package/dist/async/abortable-promise.test.js +134 -0
  6. package/dist/async/abortable-promise.test.js.map +1 -0
  7. package/dist/async.d.ts +20 -13
  8. package/dist/async.js +45 -21
  9. package/dist/async.js.map +1 -1
  10. package/dist/collections/lfu-cache.d.ts +45 -0
  11. package/dist/collections/lfu-cache.js +107 -0
  12. package/dist/collections/lfu-cache.js.map +1 -0
  13. package/dist/collections/lfu-cache.test.d.ts +1 -0
  14. package/dist/collections/lfu-cache.test.js +29 -0
  15. package/dist/collections/lfu-cache.test.js.map +1 -0
  16. package/dist/collections/linked-list.d.ts +41 -0
  17. package/dist/collections/linked-list.js +126 -0
  18. package/dist/collections/linked-list.js.map +1 -0
  19. package/dist/collections/lru-cache.d.ts +42 -0
  20. package/dist/collections/lru-cache.js +84 -0
  21. package/dist/collections/lru-cache.js.map +1 -0
  22. package/dist/collections/lru-cache.test.d.ts +1 -0
  23. package/dist/collections/lru-cache.test.js +27 -0
  24. package/dist/collections/lru-cache.test.js.map +1 -0
  25. package/dist/collections.d.ts +7 -0
  26. package/dist/collections.js +8 -0
  27. package/dist/collections.js.map +1 -0
  28. package/dist/disposable.d.ts +120 -0
  29. package/dist/disposable.js +219 -0
  30. package/dist/disposable.js.map +1 -0
  31. package/dist/fun.d.ts +6 -0
  32. package/dist/fun.js +5 -0
  33. package/dist/fun.js.map +1 -1
  34. package/dist/index.d.ts +2 -1
  35. package/dist/index.js +2 -1
  36. package/dist/index.js.map +1 -1
  37. package/package.json +27 -11
  38. package/src/async/abortable-promise.test.ts +179 -0
  39. package/src/async/abortable-promise.ts +280 -0
  40. package/src/async.ts +56 -35
  41. package/src/collections/lfu-cache.test.ts +31 -0
  42. package/src/collections/lfu-cache.ts +141 -0
  43. package/src/collections/linked-list.ts +131 -0
  44. package/src/collections/lru-cache.test.ts +29 -0
  45. package/src/collections/lru-cache.ts +109 -0
  46. package/src/collections.ts +8 -0
  47. package/src/disposable.ts +285 -0
  48. package/src/fun.ts +12 -0
  49. package/src/index.ts +2 -1
@@ -0,0 +1,280 @@
1
+ import type { Result } from "@bodil/opt";
2
+ import { Ok, Err, None, Some } from "@bodil/opt";
3
+ import { present } from "../assert";
4
+ import { eventListener } from "../disposable";
5
+ import { isAbortError } from "../async";
6
+
7
+ type Executor<A> = (
8
+ resolve: (value: A | PromiseLike<A>) => void,
9
+ reject: (error?: any) => void
10
+ ) => void;
11
+
12
+ /** Executor function for an {@link AbortablePromise}. */
13
+ export type AbortableExecutor<A, E> = (
14
+ /** Call this function to resolve the promise. */
15
+ resolve: (value: A | PromiseLike<A>) => void,
16
+ /** Call this function to reject the promise. */
17
+ reject: (error: E) => void,
18
+ /**
19
+ * The {@link AbortSignal} governing this promise. It should be passed on
20
+ * to any jobs launched by this function.
21
+ */
22
+ abort: AbortSignal
23
+ ) => void;
24
+
25
+ type AbortablePromiseConfig<A, E> = {
26
+ executor: AbortableExecutor<A, E>;
27
+ abort?: AbortSignal;
28
+ };
29
+
30
+ // I'm sure this is perfectly thread safe.
31
+ const contextParent: Array<AbortablePromise<unknown, unknown>> = [];
32
+
33
+ /**
34
+ * A promise that can be aborted using an {@link AbortSignal}.
35
+ *
36
+ * @template A The type of the resolved value of this promise.
37
+ * @template E The type of the rejected value of this promise. Defaults to
38
+ * {@link Error}, and it's usually best to keep it that way.
39
+ */
40
+ export class AbortablePromise<A, E = Error> extends Promise<A> implements Disposable {
41
+ readonly #abortController?: AbortController;
42
+ readonly #abortSignal?: AbortSignal;
43
+
44
+ /**
45
+ * Create a new {@link AbortablePromise} using an {@link AbortableExecutor}
46
+ * function and an optional {@link AbortSignal}.
47
+ *
48
+ * @param executor A function which receives two callbacks `resolve` and
49
+ * `reject` used to resolve or reject the promise, and an
50
+ * {@link AbortSignal} which should be passed on to any abortable jobs
51
+ * triggered by the function.
52
+ * @param abort An optional {@link AbortSignal} which can be used to abort
53
+ * the promise externally instead of calling its `abort()` method.
54
+ */
55
+ static run<A, E = Error>(
56
+ executor: AbortableExecutor<A, E>,
57
+ abort?: AbortSignal
58
+ ): AbortablePromise<A, E> {
59
+ return new AbortablePromise({ executor, abort });
60
+ }
61
+
62
+ /**
63
+ * Wrap any {@link PromiseLike} in an {@link AbortablePromise}.
64
+ *
65
+ * This will make the promise resolution abortable, but it has no way of
66
+ * aborting the promise while it's running.
67
+ */
68
+ static from<A, E = Error>(
69
+ promise: PromiseLike<A>,
70
+ abort?: AbortSignal
71
+ ): AbortablePromise<A, E> {
72
+ return promise instanceof AbortablePromise
73
+ ? promise
74
+ : new AbortablePromise({
75
+ executor: (resolve, reject) => void promise.then(resolve, reject),
76
+ abort,
77
+ });
78
+ }
79
+
80
+ static override resolve<A, E = Error>(
81
+ value?: A | PromiseLike<A>
82
+ ): AbortablePromise<Awaited<A>, E> {
83
+ return super.resolve(value) as AbortablePromise<Awaited<A>, E>;
84
+ }
85
+
86
+ static override reject<A = never, E = Error>(reason?: any): AbortablePromise<A, E> {
87
+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
88
+ return super.reject(reason) as AbortablePromise<A, E>;
89
+ }
90
+
91
+ static allAbortable<A extends ReadonlyArray<AbortablePromise<any>>>(
92
+ executor: (signal: AbortSignal) => A,
93
+ abort?: AbortSignal
94
+ ): AbortablePromise<{ -readonly [P in keyof A]: Awaited<A[P]> }> {
95
+ return AbortablePromise.run((resolve, reject, abort) => {
96
+ if (abort.aborted) {
97
+ reject(abort.reason);
98
+ return;
99
+ }
100
+ const jobs = executor(abort);
101
+ const running = new Set(jobs);
102
+ const results: Array<any> = [];
103
+ let failed = None;
104
+ jobs.forEach((job, index) => {
105
+ job.then(
106
+ (result) => {
107
+ results[index] = result;
108
+ running.delete(job);
109
+ if (failed.isNone() && running.size === 0) {
110
+ resolve(results as { -readonly [P in keyof A]: Awaited<A[P]> });
111
+ }
112
+ },
113
+ (error) => {
114
+ if (!isAbortError(error) && failed.isNone()) {
115
+ failed = Some(error);
116
+ running.delete(job);
117
+ reject(error);
118
+ running.forEach((job) => job.abort());
119
+ }
120
+ }
121
+ );
122
+ });
123
+ }, abort);
124
+ }
125
+
126
+ static raceAbortable<A extends AbortablePromise<any>>(
127
+ executor: (abort: AbortSignal) => ReadonlyArray<A>,
128
+ abort?: AbortSignal
129
+ ): AbortablePromise<A extends PromiseLike<infer T> ? T : never> {
130
+ return AbortablePromise.run((resolve, reject, abort) => {
131
+ if (abort.aborted) {
132
+ reject(abort.reason);
133
+ return;
134
+ }
135
+ const jobs = executor(abort);
136
+ let resolved = false;
137
+ jobs.forEach(
138
+ (job) =>
139
+ void job.then(
140
+ (result) => {
141
+ if (!resolved) {
142
+ resolved = true;
143
+ jobs.forEach((j) => {
144
+ if (j !== job) {
145
+ j.abort();
146
+ }
147
+ });
148
+ resolve(result);
149
+ }
150
+ },
151
+ (error) => {
152
+ if (!resolved) {
153
+ resolved = true;
154
+ jobs.forEach((j) => {
155
+ if (j !== job) {
156
+ j.abort();
157
+ }
158
+ });
159
+ if (!isAbortError(error)) {
160
+ reject(error);
161
+ }
162
+ }
163
+ }
164
+ )
165
+ );
166
+ }, abort);
167
+ }
168
+
169
+ private constructor(executorOrConfig: AbortablePromiseConfig<A, E> | Executor<A>) {
170
+ let executor: Executor<A>;
171
+ let abortController: AbortController | undefined = undefined;
172
+ let abortSignal: AbortSignal | undefined = undefined;
173
+ if (typeof executorOrConfig === "function") {
174
+ const context = contextParent[0];
175
+ if (context === undefined) {
176
+ // If there's no context, we need to act like a normal promise.
177
+ executor = executorOrConfig;
178
+ } else {
179
+ // If we have a context, inherit the context's abort controller.
180
+ abortController = context.#abortController;
181
+ abortSignal = context.#abortSignal;
182
+ executor = executorOrConfig;
183
+ }
184
+ } else {
185
+ const config = executorOrConfig;
186
+ abortController = new AbortController();
187
+ abortSignal = AbortSignal.any(
188
+ [abortController.signal, config.abort].filter((s) => s !== undefined)
189
+ );
190
+ executor = (resolve, reject) => {
191
+ const checkAborted = () => {
192
+ if (abortSignal!.aborted) {
193
+ reject(abortSignal!.reason);
194
+ }
195
+ return abortSignal!.aborted;
196
+ };
197
+ const listener = eventListener(abortSignal!, "abort", checkAborted, { once: true });
198
+ const wrapCleanup = <A, B>(fn: (arg: A) => B) => {
199
+ return (arg: A): B => {
200
+ listener[Symbol.dispose]();
201
+ return fn(arg);
202
+ };
203
+ };
204
+ config.executor(wrapCleanup(resolve), wrapCleanup(reject), abortSignal!);
205
+ };
206
+ }
207
+ super(executor);
208
+ this.#abortController = abortController;
209
+ this.#abortSignal = abortSignal;
210
+ }
211
+
212
+ /**
213
+ * Abort this promise.
214
+ */
215
+ abort(reason?: string) {
216
+ present(this.#abortController, "cannot abort a non-abortable Promise").abort(
217
+ new DOMException(reason, "AbortError")
218
+ );
219
+ }
220
+
221
+ /**
222
+ * The {@link AbortSignal} attached to this promise.
223
+ */
224
+ get signal(): AbortSignal {
225
+ return present(
226
+ this.#abortSignal,
227
+ "AbortablePromise: signal accessed before initialisation"
228
+ );
229
+ }
230
+
231
+ /**
232
+ * True if the promise has been aborted.
233
+ */
234
+ get aborted(): boolean {
235
+ return this.#abortSignal?.aborted ?? false;
236
+ }
237
+
238
+ /**
239
+ * Convert this promise into a promise that returns a {@link Result}.
240
+ *
241
+ * If the promise throws, it will return an {@link Err} instead of
242
+ * rejecting.
243
+ */
244
+ result(): AbortablePromise<Result<A, E>, never> {
245
+ return this.then(Ok, Err) as AbortablePromise<Result<A, E>, never>;
246
+ }
247
+
248
+ [Symbol.dispose](): void {
249
+ this.#abortController?.abort(new DOMException("disposed", "AbortError"));
250
+ }
251
+
252
+ override then<TResult1 = A, TResult2 = never>(
253
+ onfulfilled?: ((value: A) => TResult1 | PromiseLike<TResult1>) | null,
254
+ onrejected?: ((reason: E) => TResult2 | PromiseLike<TResult2>) | null
255
+ ): AbortablePromise<TResult1 | TResult2, E> {
256
+ contextParent.unshift(this);
257
+ const result = super.then(onfulfilled, onrejected) as AbortablePromise<
258
+ TResult1 | TResult2,
259
+ E
260
+ >;
261
+ void contextParent.shift();
262
+ return result;
263
+ }
264
+
265
+ override catch<TResult = never>(
266
+ onrejected?: ((reason: E) => TResult | PromiseLike<TResult>) | null
267
+ ): AbortablePromise<A | TResult, E> {
268
+ contextParent.unshift(this);
269
+ const result = super.catch(onrejected) as AbortablePromise<A | TResult, E>;
270
+ void contextParent.shift();
271
+ return result;
272
+ }
273
+
274
+ override finally(onfinally?: (() => void) | null): AbortablePromise<A, E> {
275
+ contextParent.unshift(this);
276
+ const result = super.finally(onfinally) as AbortablePromise<A, E>;
277
+ void contextParent.shift();
278
+ return result;
279
+ }
280
+ }
package/src/async.ts CHANGED
@@ -3,6 +3,59 @@
3
3
  * @module
4
4
  */
5
5
 
6
+ import { animationFrame, idleCallback, timeout, toDisposable } from "./disposable";
7
+
8
+ export { AbortablePromise, type AbortableExecutor } from "./async/abortable-promise";
9
+
10
+ /**
11
+ * Call the provided function at the soonest opportunity after the current task
12
+ * yields.
13
+ *
14
+ * This is implemented using {@link queueMicrotask}.
15
+ */
16
+ export function defer(fn: () => void | PromiseLike<void>): Disposable {
17
+ let disposed = false;
18
+ globalThis.queueMicrotask(() => {
19
+ if (disposed) {
20
+ return;
21
+ }
22
+ disposed = true;
23
+ fn();
24
+ });
25
+ return toDisposable(() => {
26
+ disposed = true;
27
+ });
28
+ }
29
+
30
+ export type SchedulerAPI = {
31
+ schedule: (job: () => void) => Disposable;
32
+ };
33
+
34
+ export const SchedulerAPI: Record<string, SchedulerAPI> = {
35
+ Microtask: {
36
+ schedule: defer,
37
+ },
38
+ Macrotask: {
39
+ schedule:
40
+ globalThis.requestIdleCallback !== undefined
41
+ ? (f) => idleCallback(f)
42
+ : (f) => timeout(f, 0),
43
+ },
44
+ AnimationFrame: {
45
+ schedule:
46
+ globalThis.requestAnimationFrame !== undefined
47
+ ? (f) => animationFrame(f)
48
+ : (f) => timeout(f, 0),
49
+ },
50
+ };
51
+
52
+ /**
53
+ * Return a promise which will resolve when the next animation frame happens.
54
+ */
55
+ export function awaitFrame(): Promise<void> {
56
+ return new Promise((resolve) => animationFrame(() => resolve()));
57
+ }
58
+
6
59
  /**
7
60
  * Return a promise that will resolve after the specified number of
8
61
  * milliseconds or {@link Temporal.Duration}.
@@ -16,41 +69,9 @@ export function sleep(duration: number | Temporal.Duration): Promise<void> {
16
69
  });
17
70
  }
18
71
 
19
- export interface AbortableJob<A> extends Disposable {
20
- result: Promise<A>;
21
- abort: (message?: string) => void;
22
- signal: AbortSignal;
23
- }
24
-
25
72
  /**
26
- * Build a promise that can be aborted using an `AbortSignal`.
27
- *
28
- * @param fn A function which receives an {@link AbortSignal} and returns a
29
- * {@link Promise}. It should pass this {@link AbortSignal} on to any abortable
30
- * jobs it creates.
31
- * @param abortController The {@link AbortController} in charge of aborting this
32
- * promise. If not provided, a new one will be constructed.
73
+ * Test whether a value is an `AbortError`.
33
74
  */
34
- export function abortable<A>(
35
- fn: (abort: AbortSignal) => Promise<A>,
36
- abortController?: AbortController
37
- ): AbortableJob<A> {
38
- abortController ??= new AbortController();
39
- return {
40
- signal: abortController.signal,
41
- result: fn(abortController.signal).then(
42
- (result) => {
43
- abortController.signal.throwIfAborted();
44
- return result;
45
- },
46
- (error) => {
47
- const aborted: boolean = abortController.signal.aborted;
48
- return aborted ? abortController.signal.reason : error;
49
- }
50
- ),
51
- abort: (message = "promise was aborted"): void =>
52
- abortController.abort(new DOMException(message, "AbortError")),
53
- [Symbol.dispose]: () =>
54
- abortController.abort(new DOMException("promise was disposed", "AbortError")),
55
- };
75
+ export function isAbortError(value: unknown): value is DOMException & { name: "AbortError" } {
76
+ return value instanceof DOMException && value.name === "AbortError";
56
77
  }
@@ -0,0 +1,31 @@
1
+ import { expect, test } from "vitest";
2
+
3
+ import { LFUCache } from "./lfu-cache";
4
+
5
+ import "@bodil/opt-vitest";
6
+
7
+ test("LFUCache", () => {
8
+ const evicted: Array<string> = [];
9
+ const cache = new LFUCache<string, string>({
10
+ maxLength: 3,
11
+ disposeFunction: (value) => evicted.push(value),
12
+ });
13
+ expect(cache.size).equal(0);
14
+ cache.set("foo", "FOO");
15
+ cache.set("bar", "BAR");
16
+ cache.set("baz", "BAZ");
17
+ expect(cache.size).equal(3);
18
+ expect(cache.get("foo")).isSome("FOO");
19
+ expect(cache.get("bar")).isSome("BAR");
20
+ expect(cache.get("baz")).isSome("BAZ");
21
+ expect(cache.get("foo")).isSome("FOO");
22
+ expect(cache.get("bar")).isSome("BAR");
23
+ expect(cache.get("wibble")).isNone();
24
+ cache.set("wibble", "WIBBLE");
25
+ expect(cache.size).equal(3);
26
+ expect(cache.get("wibble")).isSome("WIBBLE");
27
+ expect(cache.get("foo")).isSome("FOO");
28
+ expect(cache.get("bar")).isSome("BAR");
29
+ expect(cache.get("baz")).isNone();
30
+ expect(evicted).deep.equal(["BAZ"]);
31
+ });
@@ -0,0 +1,141 @@
1
+ import { None, Some, type Option } from "@bodil/opt";
2
+
3
+ import { LinkedList, type ListNode } from "./linked-list";
4
+ import { assert } from "@bodil/core/assert";
5
+ import { isDisposable } from "../disposable";
6
+
7
+ interface LFUNode<K> extends ListNode {
8
+ freq: number;
9
+ items: Set<K>;
10
+ }
11
+
12
+ interface LFURecord<K, V> {
13
+ value: V;
14
+ parent: LFUNode<K>;
15
+ }
16
+
17
+ /**
18
+ * Configuration for the {@link LFUCache}.
19
+ */
20
+ export type LFUCacheOptions<V> = {
21
+ /**
22
+ * The maximum size of the cache.
23
+ */
24
+ maxLength?: number;
25
+ /**
26
+ * An optional dispose function to be called when a value is removed from
27
+ * the cache. Defaults to disposing of values which implement
28
+ * {@link Disposable}, and doing nothing otherwise.
29
+ */
30
+ disposeFunction?: (value: V) => void;
31
+ };
32
+
33
+ function takeOne<T>(it?: Iterator<T>): Option<T> {
34
+ if (it === undefined) {
35
+ return None;
36
+ }
37
+ const result = it.next();
38
+ return result.done === true ? None : Some(result.value);
39
+ }
40
+
41
+ /**
42
+ * A Least Frequently Used cache.
43
+ *
44
+ * When the cache needs to drop a value to stay within its bounds, it chooses
45
+ * the value that has the lowest access count.
46
+ */
47
+ export class LFUCache<K, V> implements Disposable {
48
+ readonly #index = new Map<K, LFURecord<K, V>>();
49
+ #list = new LinkedList<LFUNode<K>>();
50
+ readonly #options: LFUCacheOptions<V>;
51
+
52
+ constructor(options: LFUCacheOptions<V> = {}) {
53
+ this.#options = options;
54
+ }
55
+
56
+ [Symbol.dispose](): void {
57
+ for (const record of this.#index.values()) {
58
+ this.#disposeValue(record.value);
59
+ }
60
+ this.#index.clear();
61
+ this.#list = new LinkedList();
62
+ }
63
+
64
+ #disposeValue(value: V) {
65
+ if (this.#options.disposeFunction !== undefined) {
66
+ this.#options.disposeFunction(value);
67
+ } else if (isDisposable(value)) {
68
+ value[Symbol.dispose]();
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Get the current size of the cache.
74
+ */
75
+ get size(): number {
76
+ return this.#index.size;
77
+ }
78
+
79
+ /**
80
+ * Test if the cache contains a given key.
81
+ *
82
+ * This does not count as an access towards cache invalidation.
83
+ */
84
+ has(key: K): boolean {
85
+ return this.#index.has(key);
86
+ }
87
+
88
+ /**
89
+ * Get the value associated with the given key, if it exists in the cache.
90
+ */
91
+ get(key: K): Option<V> {
92
+ const record = this.#index.get(key);
93
+ if (record === undefined) {
94
+ return None;
95
+ }
96
+ const node = record.parent;
97
+ let nextNode = node.next;
98
+ if (nextNode === undefined || nextNode.freq !== node.freq + 1) {
99
+ nextNode = this.#list.insert({ freq: node.freq + 1, items: new Set() }, node, nextNode);
100
+ }
101
+ nextNode.items.add(key);
102
+ record.parent = nextNode;
103
+ node.items.delete(key);
104
+ if (node.items.size === 0) {
105
+ this.#list.remove(node);
106
+ }
107
+ return Some(record.value);
108
+ }
109
+
110
+ /**
111
+ * Add a key/value pair to the cache.
112
+ */
113
+ set(key: K, value: V) {
114
+ let record = this.#index.get(key);
115
+ if (record !== undefined) {
116
+ if (record.value !== value) {
117
+ this.#disposeValue(record.value);
118
+ record.value = value;
119
+ }
120
+ } else {
121
+ if (this.#index.size >= (this.#options.maxLength ?? 256)) {
122
+ const head = this.#list.head;
123
+ takeOne(head?.items.keys()).ifSome((key) => {
124
+ const record = this.#index.get(key);
125
+ assert(record !== undefined);
126
+ this.#disposeValue(record.value);
127
+ head!.items.delete(key);
128
+ this.#index.delete(key);
129
+ });
130
+ }
131
+
132
+ let node = this.#list.head;
133
+ if (node === undefined || node.freq !== 1) {
134
+ node = this.#list.insert({ freq: 1, items: new Set() }, undefined, node);
135
+ }
136
+ record = { value, parent: node };
137
+ node.items.add(key);
138
+ this.#index.set(key, record);
139
+ }
140
+ }
141
+ }
@@ -0,0 +1,131 @@
1
+ import { assert } from "@bodil/core/assert";
2
+
3
+ export interface ListNode {
4
+ prev?: this;
5
+ next?: this;
6
+ }
7
+
8
+ /**
9
+ * A doubly linked list.
10
+ *
11
+ * You never know when you're going to need one.
12
+ */
13
+ export class LinkedList<Node extends ListNode> implements Iterable<Node> {
14
+ head?: Node;
15
+ tail?: Node;
16
+
17
+ /**
18
+ * Remove a node from the list.
19
+ */
20
+ remove(node: Node) {
21
+ if (node.prev !== undefined) {
22
+ node.prev.next = node.next;
23
+ } else {
24
+ assert(this.head === node);
25
+ this.head = node.next;
26
+ }
27
+ if (node.next !== undefined) {
28
+ node.next.prev = node.prev;
29
+ } else {
30
+ assert(this.tail === node);
31
+ this.tail = node.prev;
32
+ }
33
+ node.prev = undefined;
34
+ node.next = undefined;
35
+ }
36
+
37
+ /**
38
+ * Insert a node into the list between the given nodes.
39
+ *
40
+ * It goes without saying that the `prev`/`next` nodes must be adjacent to
41
+ * each other in the list, or exceptions will be thrown.
42
+ */
43
+ insert(node: Node, prev?: Node, next?: Node): Node {
44
+ assert(node.prev === undefined && node.next === undefined);
45
+ node.prev = prev;
46
+ node.next = next;
47
+ if (next !== undefined) {
48
+ assert(next.prev === prev);
49
+ next.prev = node;
50
+ }
51
+ if (prev !== undefined) {
52
+ assert(prev.next === next);
53
+ prev.next = node;
54
+ } else {
55
+ this.head = node;
56
+ }
57
+ return node;
58
+ }
59
+
60
+ /**
61
+ * Insert a node at the head of the list.
62
+ */
63
+ pushHead(node: Node) {
64
+ assert(node.prev === undefined && node.next === undefined);
65
+ if (this.head === undefined || this.tail === undefined) {
66
+ this.head = node;
67
+ this.tail = node;
68
+ } else {
69
+ node.next = this.head;
70
+ this.head.prev = node;
71
+ this.head = node;
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Insert a node at the tail of the list.
77
+ */
78
+ pushTail(node: Node) {
79
+ assert(node.prev === undefined && node.next === undefined);
80
+ if (this.head === undefined || this.tail === undefined) {
81
+ this.head = node;
82
+ this.tail = node;
83
+ } else {
84
+ node.prev = this.tail;
85
+ this.tail.next = node;
86
+ this.tail = node;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Remove the node at the head of the list and return it.
92
+ */
93
+ popHead(): Node | undefined {
94
+ const node = this.head;
95
+ if (node === undefined) {
96
+ return undefined;
97
+ }
98
+ this.head = node.next;
99
+ if (this.head === undefined) {
100
+ this.tail = undefined;
101
+ }
102
+ node.prev = undefined;
103
+ node.next = undefined;
104
+ return node;
105
+ }
106
+
107
+ /**
108
+ * Remove the node at the tail of the list and return it.
109
+ */
110
+ popTail(): Node | undefined {
111
+ const node = this.tail;
112
+ if (node === undefined) {
113
+ return undefined;
114
+ }
115
+ this.tail = node.prev;
116
+ if (this.tail === undefined) {
117
+ this.head = undefined;
118
+ }
119
+ node.prev = undefined;
120
+ node.next = undefined;
121
+ return node;
122
+ }
123
+
124
+ [Symbol.iterator] = function* (this: LinkedList<Node>): Generator<Node> {
125
+ let node = this.head;
126
+ while (node !== undefined) {
127
+ yield node;
128
+ node = node.next;
129
+ }
130
+ };
131
+ }