Merge origin/master
This commit is contained in:
+42
-2
@@ -10,6 +10,7 @@ type CacheItem<T> = {
|
||||
value: T;
|
||||
timestamp: number;
|
||||
ttl: number;
|
||||
lastAccessed: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -18,14 +19,20 @@ type CacheItem<T> = {
|
||||
class Cache {
|
||||
private storage: Map<string, CacheItem<any>>;
|
||||
private readonly defaultTTL: number;
|
||||
private readonly maxSize?: number;
|
||||
|
||||
<<<<<<< HEAD
|
||||
/**
|
||||
* Create a new cache instance
|
||||
* @param defaultTTL - Default time-to-live in milliseconds (default: 5 minutes)
|
||||
*/
|
||||
constructor(defaultTTL = 5 * 60 * 1000) { // 5 minutes default TTL
|
||||
=======
|
||||
constructor(defaultTTL = 5 * 60 * 1000, maxSize?: number) { // 5 minutes default TTL
|
||||
>>>>>>> origin/master
|
||||
this.storage = new Map();
|
||||
this.defaultTTL = defaultTTL;
|
||||
this.maxSize = maxSize;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -35,19 +42,46 @@ class Cache {
|
||||
* @param ttl - Time-to-live in milliseconds (uses default if not specified)
|
||||
*/
|
||||
set<T>(key: string, value: T, ttl = this.defaultTTL): void {
|
||||
const now = Date.now();
|
||||
|
||||
// If maxSize is set and cache is full, evict least recently used item
|
||||
if (this.maxSize && this.storage.size >= this.maxSize && !this.storage.has(key)) {
|
||||
this.evictLRU();
|
||||
}
|
||||
|
||||
this.storage.set(key, {
|
||||
value,
|
||||
timestamp: Date.now(),
|
||||
ttl
|
||||
timestamp: now,
|
||||
ttl,
|
||||
lastAccessed: now
|
||||
});
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/**
|
||||
* Retrieve a value from cache
|
||||
* Returns null if key doesn't exist or has expired
|
||||
* @param key - Cache key
|
||||
* @returns Cached value or null
|
||||
*/
|
||||
=======
|
||||
private evictLRU(): void {
|
||||
let lruKey: string | null = null;
|
||||
let lruTime = Infinity;
|
||||
|
||||
for (const [key, item] of this.storage.entries()) {
|
||||
if (item.lastAccessed < lruTime) {
|
||||
lruTime = item.lastAccessed;
|
||||
lruKey = key;
|
||||
}
|
||||
}
|
||||
|
||||
if (lruKey) {
|
||||
this.storage.delete(lruKey);
|
||||
}
|
||||
}
|
||||
|
||||
>>>>>>> origin/master
|
||||
get<T>(key: string): T | null {
|
||||
const item = this.storage.get(key);
|
||||
|
||||
@@ -58,6 +92,12 @@ class Cache {
|
||||
return null;
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
=======
|
||||
// Update last accessed time for LRU tracking
|
||||
item.lastAccessed = Date.now();
|
||||
|
||||
>>>>>>> origin/master
|
||||
return item.value;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user