Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

lruCache.ts

64 lines1.5 KB

1interface CacheEntry<T> {
2 value: T;
3 approximateSize: number;
4}
5​
6export class LRUCache<T> {
7 private cache = new Map<string, CacheEntry<T>>();
8 private totalSize = 0;
9​
10 constructor(
11 private readonly maxEntries: number,
12 private readonly maxMemoryBytes: number,
13 ) {}
14​
15 get(key: string): T | null {
16 const entry = this.cache.get(key);
17 if (!entry) {
18 return null;
19 }
20​
21 this.promote(key, entry);
22 return entry.value;
23 }
24​
25 set(key: string, value: T, approximateSize: number): void {
26 const existing = this.cache.get(key);
27 if (existing) {
28 this.totalSize -= existing.approximateSize;
29 this.cache.delete(key);
30 }
31​
32 this.evictIfNeeded(approximateSize);
33 this.cache.set(key, { value, approximateSize });
34 this.totalSize += approximateSize;
35 }
36​
37 clear(): void {
38 this.cache.clear();
39 this.totalSize = 0;
40 }
41​
42 private promote(key: string, entry: CacheEntry<T>): void {
43 this.cache.delete(key);
44 this.cache.set(key, entry);
45 }
46​
47 private evictIfNeeded(incomingSize: number): void {
48 while (
49 (this.cache.size >= this.maxEntries || this.totalSize + incomingSize > this.maxMemoryBytes) &&
50 this.cache.size > 0
51 ) {
52 const oldestKey = this.cache.keys().next().value;
53 if (oldestKey === undefined) {
54 break;
55 }
56​
57 const oldestEntry = this.cache.get(oldestKey);
58 if (oldestEntry) {
59 this.totalSize -= oldestEntry.approximateSize;
60 }
61 this.cache.delete(oldestKey);
62 }
63 }