cache.ts•980 B
interface CacheItem<T> {
data: T;
timestamp: number;
ttl: number;
}
export class SimpleCache<T> {
private cache = new Map<string, CacheItem<T>>();
private maxSize: number;
constructor(maxSize: number = 1000) {
this.maxSize = maxSize;
}
get(key: string): T | null {
const item = this.cache.get(key);
if (!item) return null;
if (Date.now() - item.timestamp > item.ttl) {
this.cache.delete(key);
return null;
}
return item.data;
}
set(key: string, data: T, ttl: number = 300000): void {
if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
if (firstKey) {
this.cache.delete(firstKey);
}
}
this.cache.set(key, {
data,
timestamp: Date.now(),
ttl
});
}
delete(key: string): boolean {
return this.cache.delete(key);
}
clear(): void {
this.cache.clear();
}
size(): number {
return this.cache.size;
}
}