| 96 | * ``` |
| 97 | */ |
| 98 | export class LruCache<K, V> extends Map<K, V> |
| 99 | implements MemoizationCache<K, V> { |
| 100 | #maxSize: number; |
| 101 | #ejecting = false; |
| 102 | #eject?: |
| 103 | | ((ejectedKey: K, ejectedValue: V, reason: LruCacheEjectionReason) => void) |
| 104 | | undefined; |
| 105 | |
| 106 | /** |
| 107 | * Constructs a new `LruCache`. |
| 108 | * |
| 109 | * @experimental **UNSTABLE**: New API, yet to be vetted. |
| 110 | * |
| 111 | * @param maxSize The maximum number of entries to store in the cache. Must |
| 112 | * be a positive integer. |
| 113 | * @param options Additional options. |
| 114 | */ |
| 115 | constructor( |
| 116 | maxSize: number, |
| 117 | options?: LruCacheOptions<K, V>, |
| 118 | ) { |
| 119 | super(); |
| 120 | if (!Number.isInteger(maxSize) || maxSize < 1) { |
| 121 | throw new RangeError( |
| 122 | `Cannot create LruCache: maxSize must be a positive integer: received ${maxSize}`, |
| 123 | ); |
| 124 | } |
| 125 | this.#maxSize = maxSize; |
| 126 | this.#eject = options?.onEject; |
| 127 | } |
| 128 | |
| 129 | /** |
| 130 | * The maximum number of entries to store in the cache. |
| 131 | * |
| 132 | * @returns The maximum number of entries in the cache. |
| 133 | * |
| 134 | * @example Max size |
| 135 | * ```ts |
| 136 | * import { LruCache } from "@std/cache"; |
| 137 | * import { assertEquals } from "@std/assert"; |
| 138 | * |
| 139 | * const cache = new LruCache<string, number>(100); |
| 140 | * assertEquals(cache.maxSize, 100); |
| 141 | * ``` |
| 142 | */ |
| 143 | get maxSize(): number { |
| 144 | return this.#maxSize; |
| 145 | } |
| 146 | |
| 147 | #setMostRecentlyUsed(key: K, value: V): void { |
| 148 | super.delete(key); |
| 149 | super.set(key, value); |
| 150 | } |
| 151 | |
| 152 | #pruneToMaxSize(): void { |
| 153 | if (this.size <= this.#maxSize) return; |
| 154 | const key = this.keys().next().value!; |
| 155 | const value = super.get(key)!; |
nothing calls this directly
no outgoing calls
no test coverage detected