35 lines
872 B
JavaScript
35 lines
872 B
JavaScript
export class SimpleCache {
|
|
constructor(maxSize = 20, ttl = 60000) {
|
|
this.cache = new Map();
|
|
this.maxSize = maxSize;
|
|
this.ttl = ttl;
|
|
}
|
|
|
|
get(key) {
|
|
const cached = this.cache.get(key);
|
|
if (!cached) return null;
|
|
if (Date.now() - cached.timestamp > this.ttl) {
|
|
this.cache.delete(key);
|
|
return null;
|
|
}
|
|
return cached.data;
|
|
}
|
|
|
|
set(key, data) {
|
|
if (this.cache.size >= this.maxSize) {
|
|
// Entferne das älteste Element
|
|
const oldest = [...this.cache.entries()].sort((a, b) => a[1].timestamp - b[1].timestamp)[0][0];
|
|
this.cache.delete(oldest);
|
|
}
|
|
this.cache.set(key, { data, timestamp: Date.now() });
|
|
}
|
|
|
|
has(key) {
|
|
return this.get(key) !== null;
|
|
}
|
|
|
|
clear() {
|
|
this.cache.clear();
|
|
}
|
|
}
|