| 174 | } |
| 175 | |
| 176 | export function asyncLruCache<ReturnType>( |
| 177 | size: number, |
| 178 | ignoreIndices: number[] = [] |
| 179 | ): (fn: AnyFunction<Promise<ReturnType>>) => AnyFunction<Promise<ReturnType>> { |
| 180 | // The cache for storing function call results. |
| 181 | const cache = new Map<string, Promise<ReturnType>>(); |
| 182 | |
| 183 | return ( |
| 184 | fn: AnyFunction<Promise<ReturnType>> |
| 185 | ): AnyFunction<Promise<ReturnType>> => { |
| 186 | return async function (...args: unknown[]): Promise<ReturnType> { |
| 187 | // Generate a cache key, ignoring specified arguments. |
| 188 | const keyArgs = args.filter((_, index) => !ignoreIndices.includes(index)); |
| 189 | const key = JSON.stringify(keyArgs); |
| 190 | |
| 191 | // Check for a cache hit. |
| 192 | if (cache.has(key)) { |
| 193 | console.log('Cache hit:', key); |
| 194 | return cache.get(key) as Promise<ReturnType>; |
| 195 | } |
| 196 | |
| 197 | // Call the original function and cache the result. |
| 198 | const result = fn(...args); |
| 199 | cache.set(key, result); |
| 200 | |
| 201 | // Check the cache size and evict the least recently used item if necessary. |
| 202 | if (cache.size > size) { |
| 203 | const oldestKey = Array.from(cache.keys())[0]; |
| 204 | cache.delete(oldestKey); |
| 205 | console.log('Evicted:', oldestKey); |
| 206 | } |
| 207 | |
| 208 | // Return the result. |
| 209 | return result; |
| 210 | }; |
| 211 | }; |
| 212 | } |