AI Code Assistant & Diff Studio
cache_legacy.ts (Before)
18 lines
1 class LegacyCache<K, V> {
2 private map = new Map<K, V>();
3 constructor(private capacity: number) {}
4
5 get(key: K): V | undefined {
6 const val = this.map.get(key);
7 if (val) {
8 - this.map.delete(key);
9 - this.map.set(key, val); // slow re-allocation
10 }
11 return val;
12 }
13 }
cache_optimized.ts (AI Refactored)
O(1) Time
1 export class FastTTLCache<K, V> {
2 private readonly cache = new Map<K, { val: V; exp: number }>();
3 + constructor(private readonly maxCap: number, private readonly ttlMs: number) {}
4
5 + get(key: K): V | undefined {
6 + const item = this.cache.get(key);
7 + if (!item) return undefined;
8 + if (Date.now() > item.exp) {
9 + this.cache.delete(key);
10 + return undefined;
11 + }
12 + return item.val;
13 + }
14 }