👁️
fork

Configure Feed

Select the types of activity you want to include in your feed.

at main 63 lines 1.3 kB view raw
1/** 2 * LRU (Least Recently Used) cache with async getOrSet support 3 */ 4export class LRUCache<K, V> { 5 private cache = new Map<K, V>(); 6 private maxSize: number; 7 8 constructor(maxSize: number) { 9 if (maxSize <= 0) { 10 throw new Error("LRU cache maxSize must be positive"); 11 } 12 this.maxSize = maxSize; 13 } 14 15 get(key: K): V | undefined { 16 const value = this.cache.get(key); 17 if (value !== undefined) { 18 this.cache.delete(key); 19 this.cache.set(key, value); 20 } 21 return value; 22 } 23 24 set(key: K, value: V): void { 25 if (this.cache.has(key)) { 26 this.cache.delete(key); 27 } else if (this.cache.size >= this.maxSize) { 28 const firstKey = this.cache.keys().next().value as K; 29 this.cache.delete(firstKey); 30 } 31 this.cache.set(key, value); 32 } 33 34 /** 35 * Get value from cache, or compute and store it if missing 36 * If factory throws, error bubbles and nothing is cached 37 */ 38 async getOrSet(key: K, factory: () => Promise<V>): Promise<V> { 39 const cached = this.get(key); 40 if (cached !== undefined) { 41 return cached; 42 } 43 44 const value = await factory(); 45 this.set(key, value); 46 return value; 47 } 48 49 clear(): void { 50 this.cache.clear(); 51 } 52 53 get size(): number { 54 return this.cache.size; 55 } 56 57 /** 58 * Check if key exists without affecting LRU order 59 */ 60 has(key: K): boolean { 61 return this.cache.has(key); 62 } 63}