I'll create a TypeScript class implementing an LRU (Least Recently Used) cache with generics for flexibility. Here's the implementation:
class LRUCache<K, V> {
private capacity: number;
private cache: Map<K, V>;
private usage: Map<K, number>;
private timestamp: number;
constructor(capacity: number) {
if (capacity <= 0) {
throw new Error('Capacity must be greater than 0');
}
this.capacity = capacity;
this.cache = new Map<K, V>();
this.usage = new Map<K, number>();
this.timestamp = 0;
}
get(key: K): V | undefined {
if (!this.cache.has(key)) {
return undefined;
}
// Update usage timestamp
this.usage.set(key, ++this.timestamp);
return this.cache.get(key);
}
put(key: K, value: V): void {
// If key exists, update value and usage
if (this.cache.has(key)) {
this.cache.set(key, value);
this.usage.set(key, ++this.timestamp);
return;
}
// If cache is full, remove least recently used item
if (this.cache.size >= this.capacity) {
let lruKey: K | null = null;
let lruTimestamp = Infinity;
// Find least recently used item
for (const [k, timestamp] of this.usage.entries()) {
if (timestamp < lruTimestamp) {
lruTimestamp = timestamp;
lruKey = k;
}
}
if (lruKey !== null) {
this.cache.delete(lruKey);
this.usage.delete(lruKey);
}
}
// Add new item
this.cache.set(key, value);
this.usage.set(key, ++this.timestamp);
}
clear(): void {
this.cache.clear();
this.usage.clear();
this.timestamp = 0;
}
size(): number {
return this.cache.size;
}
has(key: K): boolean {
return this.cache.has(key);
}
}
Here's how to use it:
// Create a cache with capacity of 3
const cache = new LRUCache<string, number>(3);
// Add some items
cache.put('a', 1);
cache.put('b', 2);
cache.put('c', 3);
console.log(cache.get('a')); // Output: 1
// Add one more item - 'b' will be evicted as it's least recently used
cache.put('d', 4);
console.log(cache.get('b')); // Output: undefined
console.log(cache.size()); // Output: 3
This implementation:
- Uses generics to support any key-value types
- Maintains O(1) lookup time for get operations
- Uses a timestamp mechanism to track usage
- Includes basic error handling
- Provides helper methods like size(), clear(), and has()
Would you like me to explain any specific part of the implementation in more detail?