(createValue: (key: string) => T, options: ScopedCacheOptions<T> = {})
| 11 | } |
| 12 | |
| 13 | export function createScopedCache<T>(createValue: (key: string) => T, options: ScopedCacheOptions<T> = {}) { |
| 14 | const store = new Map<string, Entry<T>>() |
| 15 | const now = options.now ?? Date.now |
| 16 | |
| 17 | const dispose = (key: string, entry: Entry<T>) => { |
| 18 | options.dispose?.(entry.value, key) |
| 19 | } |
| 20 | |
| 21 | const expired = (entry: Entry<T>) => { |
| 22 | if (options.ttlMs === undefined) return false |
| 23 | return now() - entry.touchedAt >= options.ttlMs |
| 24 | } |
| 25 | |
| 26 | const sweep = () => { |
| 27 | if (options.ttlMs === undefined) return |
| 28 | for (const [key, entry] of store) { |
| 29 | if (!expired(entry)) continue |
| 30 | store.delete(key) |
| 31 | dispose(key, entry) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | const touch = (key: string, entry: Entry<T>) => { |
| 36 | entry.touchedAt = now() |
| 37 | store.delete(key) |
| 38 | store.set(key, entry) |
| 39 | } |
| 40 | |
| 41 | const prune = () => { |
| 42 | if (options.maxEntries === undefined) return |
| 43 | while (store.size > options.maxEntries) { |
| 44 | const key = store.keys().next().value |
| 45 | if (!key) return |
| 46 | const entry = store.get(key) |
| 47 | store.delete(key) |
| 48 | if (!entry) continue |
| 49 | dispose(key, entry) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | const remove = (key: string) => { |
| 54 | const entry = store.get(key) |
| 55 | if (!entry) return |
| 56 | store.delete(key) |
| 57 | dispose(key, entry) |
| 58 | return entry.value |
| 59 | } |
| 60 | |
| 61 | const peek = (key: string) => { |
| 62 | sweep() |
| 63 | const entry = store.get(key) |
| 64 | if (!entry) return |
| 65 | if (!expired(entry)) return entry.value |
| 66 | store.delete(key) |
| 67 | dispose(key, entry) |
| 68 | } |
| 69 | |
| 70 | const get = (key: string) => { |
no outgoing calls
no test coverage detected