( f: (...args: Args) => Result, cacheFn: (...args: Args) => string, maxCacheSize: number = 100, )
| 232 | * @returns A memoized version of the function with cache management methods |
| 233 | */ |
| 234 | export function memoizeWithLRU< |
| 235 | Args extends unknown[], |
| 236 | Result extends NonNullable<unknown>, |
| 237 | >( |
| 238 | f: (...args: Args) => Result, |
| 239 | cacheFn: (...args: Args) => string, |
| 240 | maxCacheSize: number = 100, |
| 241 | ): LRUMemoizedFunction<Args, Result> { |
| 242 | const cache = new LRUCache<string, Result>({ |
| 243 | max: maxCacheSize, |
| 244 | }) |
| 245 | |
| 246 | const memoized = (...args: Args): Result => { |
| 247 | const key = cacheFn(...args) |
| 248 | const cached = cache.get(key) |
| 249 | if (cached !== undefined) { |
| 250 | return cached |
| 251 | } |
| 252 | |
| 253 | const result = f(...args) |
| 254 | cache.set(key, result) |
| 255 | return result |
| 256 | } |
| 257 | |
| 258 | // Add cache management methods |
| 259 | memoized.cache = { |
| 260 | clear: () => cache.clear(), |
| 261 | size: () => cache.size, |
| 262 | delete: (key: string) => cache.delete(key), |
| 263 | // peek() avoids updating recency — we only want to observe, not promote |
| 264 | get: (key: string) => cache.peek(key), |
| 265 | has: (key: string) => cache.has(key), |
| 266 | } |
| 267 | |
| 268 | return memoized |
| 269 | } |
no test coverage detected