Files
Portfolio/src/utils/cache.ts
T
2026-01-25 19:45:16 +01:00

133 lines
2.9 KiB
TypeScript

/**
* In-Memory Cache Utility
* Provides simple key-value caching with TTL (Time To Live) support
*/
/**
* Cache item structure with value, timestamp, and TTL
*/
type CacheItem<T> = {
value: T;
timestamp: number;
ttl: number;
lastAccessed: number;
};
/**
* In-memory cache implementation with automatic expiration
*/
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;
}
/**
* Store a value in cache with optional TTL
* @param key - Cache key
* @param value - Value to 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: 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);
if (!item) return null;
if (Date.now() > item.timestamp + item.ttl) {
this.storage.delete(key);
return null;
}
<<<<<<< HEAD
=======
// Update last accessed time for LRU tracking
item.lastAccessed = Date.now();
>>>>>>> origin/master
return item.value;
}
/**
* Check if a key exists and is not expired
* @param key - Cache key
* @returns True if key exists and is valid
*/
has(key: string): boolean {
return this.get(key) !== null;
}
/**
* Remove a specific key from cache
* @param key - Cache key to delete
*/
delete(key: string): void {
this.storage.delete(key);
}
/**
* Clear all cached items
*/
clear(): void {
this.storage.clear();
}
}
/**
* Shared cache instance with 5-minute default TTL
*/
export const cache = new Cache();