@bodil/core 0.3.1 → 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 (47) 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.js.map +1 -1
  32. package/dist/index.d.ts +2 -1
  33. package/dist/index.js +2 -1
  34. package/dist/index.js.map +1 -1
  35. package/package.json +27 -11
  36. package/src/async/abortable-promise.test.ts +179 -0
  37. package/src/async/abortable-promise.ts +280 -0
  38. package/src/async.ts +56 -35
  39. package/src/collections/lfu-cache.test.ts +31 -0
  40. package/src/collections/lfu-cache.ts +141 -0
  41. package/src/collections/linked-list.ts +131 -0
  42. package/src/collections/lru-cache.test.ts +29 -0
  43. package/src/collections/lru-cache.ts +109 -0
  44. package/src/collections.ts +8 -0
  45. package/src/disposable.ts +285 -0
  46. package/src/fun.ts +0 -2
  47. package/src/index.ts +2 -1
@@ -0,0 +1,29 @@
1
+ import { expect, test } from "vitest";
2
+
3
+ import { LRUCache } from "./lru-cache";
4
+
5
+ import "@bodil/opt-vitest";
6
+
7
+ test("LRUCache", () => {
8
+ const evicted: Array<string> = [];
9
+ const cache = new LRUCache<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("baz")).isSome("BAZ");
19
+ expect(cache.get("bar")).isSome("BAR");
20
+ expect(cache.get("foo")).isSome("FOO");
21
+ expect(cache.get("wibble")).isNone();
22
+ cache.set("wibble", "WIBBLE");
23
+ expect(cache.size).equal(3);
24
+ expect(cache.get("wibble")).isSome("WIBBLE");
25
+ expect(cache.get("foo")).isSome("FOO");
26
+ expect(cache.get("bar")).isSome("BAR");
27
+ expect(cache.get("baz")).isNone();
28
+ expect(evicted).deep.equal(["BAZ"]);
29
+ });
@@ -0,0 +1,109 @@
1
+ import { None, Some, type Option } from "@bodil/opt";
2
+ import { assert } from "@bodil/core/assert";
3
+
4
+ import { LinkedList, type ListNode } from "./linked-list";
5
+ import { isDisposable } from "../disposable";
6
+
7
+ interface LRUNode<K, V> extends ListNode {
8
+ key: K;
9
+ value: V;
10
+ }
11
+
12
+ export type LRUCacheOptions<V> = {
13
+ /**
14
+ * The maximum size of the cache.
15
+ */
16
+ maxLength?: number;
17
+ /**
18
+ * An optional dispose function to be called when a value is removed from
19
+ * the cache. Defaults to disposing of values which implement
20
+ * {@link Disposable}, and doing nothing otherwise.
21
+ */
22
+ disposeFunction?: (value: V) => void;
23
+ };
24
+
25
+ /**
26
+ * A Least Recently Used cache.
27
+ *
28
+ * When the cache needs to drop a value to stay within its bounds, it chooses
29
+ * the value that was accessed the least recently.
30
+ */
31
+ export class LRUCache<K, V> implements Disposable {
32
+ readonly #index = new Map<K, LRUNode<K, V>>();
33
+ #list = new LinkedList<LRUNode<K, V>>();
34
+ readonly #options: LRUCacheOptions<V>;
35
+
36
+ constructor(options: LRUCacheOptions<V> = {}) {
37
+ this.#options = options;
38
+ }
39
+
40
+ [Symbol.dispose](): void {
41
+ for (const node of this.#index.values()) {
42
+ this.#disposeValue(node.value);
43
+ }
44
+ this.#index.clear();
45
+ this.#list = new LinkedList();
46
+ }
47
+
48
+ #disposeValue(value: V) {
49
+ if (this.#options.disposeFunction !== undefined) {
50
+ this.#options.disposeFunction(value);
51
+ } else if (isDisposable(value)) {
52
+ value[Symbol.dispose]();
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Get the current size of the cache.
58
+ */
59
+ get size(): number {
60
+ return this.#index.size;
61
+ }
62
+
63
+ /**
64
+ * Test if the cache contains a given key.
65
+ *
66
+ * This does not count as an access towards cache invalidation.
67
+ */
68
+ has(key: K): boolean {
69
+ return this.#index.has(key);
70
+ }
71
+
72
+ /**
73
+ * Get the value associated with the given key, if it exists in the cache.
74
+ */
75
+ get(key: K): Option<V> {
76
+ const node = this.#index.get(key);
77
+ if (node === undefined) {
78
+ return None;
79
+ }
80
+ this.#list.remove(node);
81
+ this.#list.pushHead(node);
82
+ return Some(node.value);
83
+ }
84
+
85
+ /**
86
+ * Add a key/value pair to the cache.
87
+ */
88
+ set(key: K, value: V) {
89
+ let node = this.#index.get(key);
90
+ if (node !== undefined) {
91
+ this.#list.remove(node);
92
+ if (node.value !== value) {
93
+ this.#disposeValue(node.value);
94
+ node.value = value;
95
+ }
96
+ } else {
97
+ node = { key, value };
98
+ this.#index.set(key, node);
99
+ }
100
+ this.#list.pushHead(node);
101
+
102
+ while (this.#index.size > (this.#options.maxLength ?? 256)) {
103
+ const expiredNode = this.#list.popTail();
104
+ assert(expiredNode !== undefined);
105
+ this.#index.delete(expiredNode.key);
106
+ this.#disposeValue(expiredNode.value);
107
+ }
108
+ }
109
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Some useful data structures.
3
+ * @module
4
+ */
5
+
6
+ export { LinkedList, type ListNode } from "./collections/linked-list";
7
+ export { LFUCache, type LFUCacheOptions } from "./collections/lfu-cache";
8
+ export { LRUCache, type LRUCacheOptions } from "./collections/lru-cache";
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Tools for working with {@link Disposable}s and things that should have been
3
+ * {@link Disposable}.
4
+ *
5
+ * @module
6
+ */
7
+
8
+ import { assert } from "@bodil/core/assert";
9
+ import type { Constructor, Unsubscribable } from "type-fest";
10
+ import type { ExtractEventMap } from "@bodil/core/event";
11
+
12
+ // @ts-ignore polyfill Symbol.dispose if missing
13
+ Symbol.dispose ??= Symbol.for("Symbol.dispose");
14
+
15
+ /**
16
+ * Test whether something implements {@link Disposable}.
17
+ */
18
+ export function isDisposable(value: unknown): value is Disposable {
19
+ try {
20
+ return typeof (value as Disposable)[Symbol.dispose] === "function";
21
+ } catch (_e) {
22
+ return false;
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Type for something that can be turned into a {@link Disposable}.
28
+ *
29
+ * Includes things that already implement {@link Disposable}, objects with an
30
+ * `unsubscribe()` method (an {@link Unsubscribable}), and functions
31
+ * with no arguments or return values which are assumed to be unsubscribe
32
+ * functions, as popularised by React.
33
+ */
34
+ export type Disposifiable = (() => void) | Unsubscribable | Disposable;
35
+
36
+ function extractDisposeFn(value: Disposifiable): () => void {
37
+ if (typeof value === "function") {
38
+ return value;
39
+ }
40
+ if (typeof value === "object") {
41
+ if (typeof (value as Disposable)[Symbol.dispose] === "function") {
42
+ return (value as Disposable)[Symbol.dispose].bind(value);
43
+ }
44
+ if (typeof (value as Unsubscribable).unsubscribe === "function") {
45
+ return (value as Unsubscribable).unsubscribe.bind(value);
46
+ }
47
+ }
48
+ throw new Error("toDisposable(): don't know how to convert given value to disposable");
49
+ }
50
+
51
+ /**
52
+ * Construct a new {@link Disposable} out of any {@link Disposifiable}.
53
+ *
54
+ * This constructs a new object which implements {@link Disposable}, and nothing
55
+ * else. The new object's dispose method will dispose of the original
56
+ * {@link Disposifiable}, and ensure that this happens only once, regardless of
57
+ * how many times the dispose method is called.
58
+ */
59
+ export function toDisposable(value: Disposifiable): Disposable {
60
+ let disposed = false;
61
+ const disposeFn = extractDisposeFn(value);
62
+ return {
63
+ [Symbol.dispose](): void {
64
+ if (!disposed) {
65
+ disposed = true;
66
+ disposeFn();
67
+ }
68
+ },
69
+ };
70
+ }
71
+
72
+ /**
73
+ * Attach an event listener to an {@link EventTarget} and return a
74
+ * {@link Disposable} which will remove the listener when disposed.
75
+ */
76
+ export function eventListener<
77
+ T extends EventTarget,
78
+ M extends ExtractEventMap<T>,
79
+ K extends keyof M & string
80
+ >(
81
+ target: T,
82
+ type: K,
83
+ callback: (e: M[K]) => any,
84
+ options?: AddEventListenerOptions | boolean
85
+ ): Disposable {
86
+ target.addEventListener(type, callback as EventListener, options);
87
+ return toDisposable(() => target.removeEventListener(type, callback as EventListener));
88
+ }
89
+
90
+ /**
91
+ * Call {@link setTimeout} with the provided callback and return a
92
+ * {@link Disposable} which will cancel the timeout when disposed.
93
+ */
94
+ export function timeout(fn: () => void, timeout: number | Temporal.Duration): Disposable {
95
+ let id: number | null = globalThis.setTimeout(
96
+ () => {
97
+ id = null;
98
+ disposable[Symbol.dispose]();
99
+ fn();
100
+ },
101
+ typeof timeout === "number" ? timeout : timeout.total("milliseconds")
102
+ );
103
+ const disposable = toDisposable(() => {
104
+ if (id !== null) {
105
+ clearTimeout(id);
106
+ }
107
+ });
108
+ return disposable;
109
+ }
110
+
111
+ /**
112
+ * Call {@link setInterval} with the provided callback and return a
113
+ * {@link Disposable} which will cancel the interval when disposed.
114
+ */
115
+ export function interval(fn: () => void, interval: number | Temporal.Duration): Disposable {
116
+ const id = globalThis.setInterval(
117
+ fn,
118
+ typeof interval === "number" ? interval : interval.total("milliseconds")
119
+ );
120
+ return toDisposable(() => {
121
+ clearInterval(id);
122
+ });
123
+ }
124
+
125
+ /**
126
+ * Call {@link window.requestAnimationFrame} with the provided callback and return a
127
+ * {@link Disposable} which will cancel the request when disposed.
128
+ */
129
+ export function animationFrame(fn: (time: number) => void): Disposable {
130
+ // @ts-ignore requestAnimationFrame is only available in browser contexts
131
+ let id: number | null = globalThis.requestAnimationFrame((time) => {
132
+ id = null;
133
+ fn(time);
134
+ disposable[Symbol.dispose]();
135
+ });
136
+ const disposable = toDisposable(() => {
137
+ if (id !== null) {
138
+ // @ts-ignore cancelAnimationFrame is only available in browser contexts
139
+ globalThis.cancelAnimationFrame(id);
140
+ }
141
+ });
142
+ return disposable;
143
+ }
144
+
145
+ export function idleCallback(
146
+ callback: IdleRequestCallback,
147
+ options?: IdleRequestOptions
148
+ ): Disposable {
149
+ let id: number | null = globalThis.requestIdleCallback((deadline: IdleDeadline) => {
150
+ id = null;
151
+ disposable[Symbol.dispose]();
152
+ callback(deadline);
153
+ }, options);
154
+ const disposable = toDisposable(() => {
155
+ if (id !== null) {
156
+ globalThis.cancelIdleCallback(id);
157
+ }
158
+ });
159
+ return disposable;
160
+ }
161
+
162
+ /**
163
+ * An implementation of {@link AbortController} which also implements
164
+ * {@link Disposable}.
165
+ *
166
+ * Disposing the controller automatically triggers the abort signal.
167
+ */
168
+ export class DisposableAbortController implements AbortController, Disposable {
169
+ #controller = new AbortController();
170
+
171
+ get signal(): AbortSignal {
172
+ return this.#controller.signal;
173
+ }
174
+
175
+ abort(reason?: any): void {
176
+ this.#controller.abort(reason);
177
+ this.#controller = new AbortController();
178
+ }
179
+
180
+ [Symbol.dispose](): void {
181
+ this.abort("disposed");
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Create an {@link AbortController} which also implements {@link Disposable}.
187
+ *
188
+ * Disposing the controller automatically triggers the abort signal.
189
+ *
190
+ * @returns A {@link DisposableAbortController}.
191
+ */
192
+ export function abortController(): DisposableAbortController {
193
+ return new DisposableAbortController();
194
+ }
195
+
196
+ /**
197
+ * A reentrant version of {@link DisposableStack}.
198
+ *
199
+ * This maintains a list of {@link Disposable}s, added with the
200
+ * {@link DisposableContext.use} method, which will all be disposed when you
201
+ * dispose of the {@link DisposableContext} itself.
202
+ *
203
+ * Where this differs from {@link DisposableStack} is that disposing it only
204
+ * resets it after disposing of its dependents, and you can reuse it as many
205
+ * times as you like. This is very handy for managing lifecycle resources, eg. a
206
+ * web component can allocate resources in its `connectedCallback` method and
207
+ * during its connected lifecycle phase which can all be disposed in
208
+ * `disconnectedCallback` with a single call to
209
+ * {@link DisposableContext.dispose}, and it's instantly ready to go again on
210
+ * reconnect.
211
+ */
212
+ export class DisposableContext implements Disposable {
213
+ readonly #disposables = new Set<Disposable>();
214
+
215
+ dispose = this[Symbol.dispose];
216
+ [Symbol.dispose](): void {
217
+ if (this.#disposables.size === 0) {
218
+ return;
219
+ }
220
+ for (const disposable of this.#disposables) {
221
+ disposable[Symbol.dispose]();
222
+ }
223
+ assert(
224
+ this.#disposables.size === 0,
225
+ "DisposableContext: disposables remaining in context after dispose, this isn't supposed to happen"
226
+ );
227
+ }
228
+
229
+ /**
230
+ * Register a {@link Disposifiable} resource with this context, to be
231
+ * disposed along with it.
232
+ *
233
+ * @returns The {@link Disposable} that was registered with the context.
234
+ */
235
+ use(resource: null): null;
236
+ use(resource: undefined): undefined;
237
+ use(resource: Disposifiable): Disposable;
238
+ use(resource: Disposifiable | undefined): Disposable | undefined;
239
+ use(resource: Disposifiable | null | undefined): Disposable | null | undefined;
240
+ use(resource: Disposifiable | null | undefined): Disposable | null | undefined {
241
+ if (resource === undefined || resource === null) {
242
+ return resource;
243
+ }
244
+ let disposables: Set<Disposable> | undefined = this.#disposables;
245
+ const dispose = extractDisposeFn(resource);
246
+ const wrappedDisposable = {
247
+ [Symbol.dispose](): void {
248
+ if (disposables?.delete(wrappedDisposable) === true) {
249
+ dispose();
250
+ }
251
+ disposables = undefined;
252
+ },
253
+ };
254
+ disposables.add(wrappedDisposable);
255
+ return wrappedDisposable;
256
+ }
257
+ }
258
+
259
+ /**
260
+ * A class mixin which provides a {@link Disposable} implementation.
261
+ *
262
+ * The `use(resource)` method can be used to register {@link Disposifiable}
263
+ * resources which will be disposed when the object's dispose method is called.
264
+ */
265
+ export const AutoDisposable = <C extends Constructor<object>>(superclass: C) =>
266
+ class extends superclass implements Disposable {
267
+ #_context?: DisposableContext = new DisposableContext();
268
+
269
+ [Symbol.dispose](): void {
270
+ if (this.#_context !== undefined) {
271
+ this.#_context.dispose();
272
+ this.#_context = undefined;
273
+ }
274
+ }
275
+
276
+ use(resource: null): null;
277
+ use(resource: undefined): undefined;
278
+ use(resource: Disposifiable): Disposable;
279
+ use(resource: Disposifiable | undefined): Disposable | undefined;
280
+ use(resource: Disposifiable | null | undefined): Disposable | null | undefined;
281
+ use(resource: Disposifiable | null | undefined): Disposable | null | undefined {
282
+ assert(this.#_context, "AutoDisposable: use() called after dispose");
283
+ return this.#_context.use(resource);
284
+ }
285
+ };
package/src/fun.ts CHANGED
@@ -3,8 +3,6 @@
3
3
  * @module
4
4
  */
5
5
 
6
- import { OperatorComparable } from "./order";
7
-
8
6
  /**
9
7
  * Create a function that always returns `value`.
10
8
  */
package/src/index.ts CHANGED
@@ -5,9 +5,10 @@
5
5
 
6
6
  import * as assert from "./assert";
7
7
  import * as async from "./async";
8
+ import * as disposable from "./disposable";
8
9
  import * as event from "./event";
9
10
  import * as fun from "./fun";
10
11
  import * as order from "./order";
11
12
  import * as time from "./time";
12
13
  import * as types from "./types";
13
- export { assert, async, event, fun, order, time, types };
14
+ export { assert, async, disposable, event, fun, order, time, types };