All files / cache / lru_cache.ts

100.00% Branches 40/40
100.00% Functions 11/11
100.00% Lines 105/105
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x16
 
x16
x38
x16
 
 
 
 
 
 
 
 
 
 
 
 
x16
x16
x16
x16
x38
x38
x5
x5
 
x5
x33
x38
x38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x16
x2
x2
 
x16
x288
x288
x288
 
x16
x177
x15
x15
x15
x177
x5
x5
x5
x5
x5
x5
x5
x177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x16
x9
x9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x16
x222
x111
x111
x111
x111
 
x111
x222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x16
x5
x5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x16
x178
x1
x1
 
x1
x177
x177
 
x177
x178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x16
x12
x1
x1
 
x1
x11
x11
x12
 
x12
x8
x8
x8
x8
x8
x8
x8
x8
x12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x16
x6
x1
x1
 
x1
x6
x2
x2
x2
x3
x3
x3
x3
x3
x5
x9
x9
x9
x4
x4
x9
x3
x3
x3
x5
x6
x16








































































































































































































































































































































































// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.

import type { MemoizationCache } from "./memoize.ts";
export type { MemoizationCache };

/**
 * The reason an entry was removed from the cache.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * - `"evicted"` — removed automatically because the cache exceeded
 *   {@linkcode LruCache.prototype.maxSize | maxSize}.
 * - `"deleted"` — removed by an explicit
 *   {@linkcode LruCache.prototype.delete | delete()} call.
 * - `"cleared"` — removed by
 *   {@linkcode LruCache.prototype.clear | clear()}.
 */
export type LruCacheEjectionReason = "evicted" | "deleted" | "cleared";

/**
 * Options for the {@linkcode LruCache} constructor.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 */
export interface LruCacheOptions<K, V> {
  /**
   * Callback invoked when an entry is removed, whether by eviction,
   * manual deletion, or clearing the cache. The entry is already removed
   * from the cache when this callback fires. Overwriting an existing key
   * via {@linkcode LruCache.prototype.set | set()} does **not** trigger
   * this callback. The cache is not re-entrant during this callback:
   * calling `set`, `delete`, or `clear` will throw.
   *
   * @param ejectedKey The key of the removed entry.
   * @param ejectedValue The value of the removed entry.
   * @param reason Why the entry was removed.
   */
  onEject?: (
    ejectedKey: K,
    ejectedValue: V,
    reason: LruCacheEjectionReason,
  ) => void;
}

/**
 * Least-recently-used cache.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @see {@link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU | Least-recently-used cache}
 *
 * Automatically removes entries above the max size based on when they were
 * last accessed with `get` or `set`.
 *
 * @typeParam K The type of the cache keys.
 * @typeParam V The type of the cache values.
 *
 * @example Basic usage
 * ```ts
 * import { LruCache } from "@std/cache";
 * import { assert, assertEquals } from "@std/assert";
 *
 * const MAX_SIZE = 3;
 * const cache = new LruCache<string, number>(MAX_SIZE);
 *
 * cache.set("a", 1);
 * cache.set("b", 2);
 * cache.set("c", 3);
 * cache.set("d", 4);
 *
 * // most recent values are stored up to `MAX_SIZE`
 * assertEquals(cache.get("b"), 2);
 * assertEquals(cache.get("c"), 3);
 * assertEquals(cache.get("d"), 4);
 *
 * // less recent values are removed
 * assert(!cache.has("a"));
 * ```
 *
 * @example Adding an onEject callback
 * ```ts
 * import { LruCache } from "@std/cache";
 * import { assertEquals } from "@std/assert";
 *
 * const ejected: [string, number, string][] = [];
 * const cache = new LruCache<string, number>(2, {
 *   onEject: (key, value, reason) => ejected.push([key, value, reason]),
 * });
 *
 * cache.set("a", 1);
 * cache.set("b", 2);
 * cache.set("c", 3);
 *
 * assertEquals(ejected, [["a", 1, "evicted"]]);
 * ```
 */
export class LruCache<K, V> extends Map<K, V>
  implements MemoizationCache<K, V> {
  #maxSize: number;
  #ejecting = false;
  #eject?:
    | ((ejectedKey: K, ejectedValue: V, reason: LruCacheEjectionReason) => void)
    | undefined;

  /**
   * Constructs a new `LruCache`.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @param maxSize The maximum number of entries to store in the cache. Must
   * be a positive integer.
   * @param options Additional options.
   */
  constructor(
    maxSize: number,
    options?: LruCacheOptions<K, V>,
  ) {
    super();
    if (!Number.isInteger(maxSize) || maxSize < 1) {
      throw new RangeError(
        `Cannot create LruCache: maxSize must be a positive integer: received ${maxSize}`,
      );
    }
    this.#maxSize = maxSize;
    this.#eject = options?.onEject;
  }

  /**
   * The maximum number of entries to store in the cache.
   *
   * @returns The maximum number of entries in the cache.
   *
   * @example Max size
   * ```ts
   * import { LruCache } from "@std/cache";
   * import { assertEquals } from "@std/assert";
   *
   * const cache = new LruCache<string, number>(100);
   * assertEquals(cache.maxSize, 100);
   * ```
   */
  get maxSize(): number {
    return this.#maxSize;
  }

  #setMostRecentlyUsed(key: K, value: V): void {
    super.delete(key);
    super.set(key, value);
  }

  #pruneToMaxSize(): void {
    if (this.size <= this.#maxSize) return;
    const key = this.keys().next().value!;
    const value = super.get(key)!;
    super.delete(key);
    if (this.#eject) {
      this.#ejecting = true;
      try {
        this.#eject(key, value, "evicted");
      } finally {
        this.#ejecting = false;
      }
    }
  }

  /**
   * Checks whether an element with the specified key exists or not. Does
   * **not** update the entry's position in the eviction order.
   *
   * @param key The key to check.
   * @returns `true` if the cache contains the specified key, otherwise `false`.
   *
   * @example Checking for the existence of a key
   * ```ts
   * import { LruCache } from "@std/cache";
   * import { assert } from "@std/assert";
   *
   * const cache = new LruCache<string, number>(100);
   *
   * cache.set("a", 1);
   * assert(cache.has("a"));
   * ```
   */
  override has(key: K): boolean {
    return super.has(key);
  }

  /**
   * Gets the element with the specified key.
   *
   * @param key The key to get the value for.
   * @returns The value associated with the specified key, or `undefined` if
   * the key is not present in the cache.
   *
   * @example Getting a value from the cache
   * ```ts
   * import { LruCache } from "@std/cache";
   * import { assertEquals } from "@std/assert";
   *
   * const cache = new LruCache<string, number>(100);
   *
   * cache.set("a", 1);
   * assertEquals(cache.get("a"), 1);
   * ```
   */
  override get(key: K): V | undefined {
    if (super.has(key)) {
      const value = super.get(key)!;
      this.#setMostRecentlyUsed(key, value);
      return value;
    }

    return undefined;
  }

  /**
   * Returns the value associated with the given key, or `undefined` if the
   * key is not present, **without** updating its position in the eviction
   * order.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @param key The key to look up.
   * @returns The value, or `undefined` if not present.
   *
   * @example Peeking at a value without promoting it
   * ```ts
   * import { LruCache } from "@std/cache";
   * import { assertEquals } from "@std/assert";
   *
   * const cache = new LruCache<string, number>(3);
   * cache.set("a", 1);
   * cache.set("b", 2);
   * cache.set("c", 3);
   *
   * // peek does not promote "a"
   * assertEquals(cache.peek("a"), 1);
   *
   * // "a" is still the least recently used and gets evicted
   * cache.set("d", 4);
   * assertEquals(cache.peek("a"), undefined);
   * ```
   */
  peek(key: K): V | undefined {
    return super.get(key);
  }

  /**
   * Sets the specified key to the specified value.
   *
   * @param key The key to set the value for.
   * @param value The value to set.
   * @returns `this` for chaining.
   *
   * @example Setting a value in the cache
   * ```ts no-assert
   * import { LruCache } from "@std/cache";
   *
   * const cache = new LruCache<string, number>(100);
   * cache.set("a", 1);
   * ```
   */
  override set(key: K, value: V): this {
    if (this.#ejecting) {
      throw new TypeError(
        "Cannot set entry in LruCache: cache is not re-entrant during onEject callbacks",
      );
    }
    this.#setMostRecentlyUsed(key, value);
    this.#pruneToMaxSize();

    return this;
  }

  /**
   * Deletes the value associated with the given key.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @param key The key to delete.
   * @returns `true` if the key was deleted, `false` otherwise.
   *
   * @example Deleting a key from the cache
   * ```ts
   * import { LruCache } from "@std/cache";
   * import { assertEquals } from "@std/assert/equals";
   *
   * const cache = new LruCache<string, number>(1);
   *
   * cache.set("a", 1);
   * cache.delete("a");
   * assertEquals(cache.has("a"), false);
   * ```
   */
  override delete(key: K): boolean {
    if (this.#ejecting) {
      throw new TypeError(
        "Cannot delete entry in LruCache: cache is not re-entrant during onEject callbacks",
      );
    }
    const value = super.get(key);
    const existed = super.delete(key);
    if (!existed) return false;

    if (this.#eject) {
      this.#ejecting = true;
      try {
        this.#eject(key, value!, "deleted");
      } finally {
        this.#ejecting = false;
      }
    }
    return true;
  }

  /**
   * Clears the cache.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @example Usage
   * ```ts
   * import { LruCache } from "@std/cache";
   * import { assertEquals } from "@std/assert/equals";
   *
   * const cache = new LruCache<string, number>(100);
   *
   * cache.set("a", 1);
   * cache.set("b", 2);
   * cache.clear();
   * assertEquals(cache.size, 0);
   * ```
   */
  override clear(): void {
    if (this.#ejecting) {
      throw new TypeError(
        "Cannot clear LruCache: cache is not re-entrant during onEject callbacks",
      );
    }
    if (!this.#eject) {
      super.clear();
      return;
    }
    const entries = [...super.entries()];
    super.clear();
    this.#ejecting = true;
    let error: unknown;
    try {
      for (const [key, value] of entries) {
        try {
          this.#eject(key, value, "cleared");
        } catch (e) {
          error ??= e;
        }
      }
    } finally {
      this.#ejecting = false;
    }
    if (error !== undefined) throw error;
  }
}