* Get or compute a cached value
(
key: string,
data: unknown,
computeFn: () => T,
options?: { ttl?: number; forceRecompute?: boolean }
)
| 61 | * Get or compute a cached value |
| 62 | */ |
| 63 | getOrCompute<T>( |
| 64 | key: string, |
| 65 | data: unknown, |
| 66 | computeFn: () => T, |
| 67 | options?: { ttl?: number; forceRecompute?: boolean } |
| 68 | ): T { |
| 69 | const dataHash = this.hashData(data); |
| 70 | const cacheKey = `${key}:${dataHash}`; |
| 71 | const now = Date.now(); |
| 72 | const ttl = options?.ttl ?? this.maxAge; |
| 73 | |
| 74 | // Check if we have a valid cached entry |
| 75 | if (!options?.forceRecompute) { |
| 76 | const entry = this.cache.get(cacheKey); |
| 77 | if (entry && (now - entry.timestamp) < ttl) { |
| 78 | return entry.value as T; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // Compute new value |
| 83 | const value = computeFn(); |
| 84 | |
| 85 | // Store in cache |
| 86 | this.cache.set(cacheKey, { |
| 87 | value, |
| 88 | timestamp: now, |
| 89 | dataHash, |
| 90 | }); |
| 91 | |
| 92 | // Evict old entries if cache is too large |
| 93 | this.evictIfNeeded(); |
| 94 | |
| 95 | return value; |
| 96 | } |
| 97 | |
| 98 | /** |
| 99 | * Get a cached value without computing (returns undefined if not cached) |
no test coverage detected