Function
cachedFactory
(factory: (key: K) => V, size: number)
Source from the content-addressed store, hash-verified
| 1 | export function cachedFactory<K, V>(factory: (key: K) => V, size: number): (key: K) => V { |
| 2 | const cache = new Map<K, V>(); |
| 3 | |
| 4 | return (key: K) => { |
| 5 | if (cache.has(key)) { |
| 6 | return cache.get(key)!; |
| 7 | } |
| 8 | const value = factory(key); |
| 9 | cache.set(key, value); |
| 10 | if (cache.size > size) { |
| 11 | const first = cache.keys().next().value!; |
| 12 | cache.delete(first); |
| 13 | } |
| 14 | return value; |
| 15 | }; |
| 16 | } |
Tested by
no test coverage detected