تمرين إعادة البناء
Expiring Cache
أعد كتابة cache عام في TypeScript يحذف القيم بعد انتهاء مدتها.
typescript
~15 دقيقة
متوسط
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
interface CacheEntry<T> {
value: T;
expiresAt: number;
}
class ExpiringCache<T> {
private readonly entries = new Map<string, CacheEntry<T>>();
set(key: string, value: T, ttlMilliseconds: number): void {
this.entries.set(key, {
value,
expiresAt: Date.now() + ttlMilliseconds,
});
}
get(key: string): T | undefined {
const entry = this.entries.get(key);
if (!entry) {
return undefined;
}
if (entry.expiresAt <= Date.now()) {
this.entries.delete(key);
return undefined;
}
return entry.value;
}
keys(): string[] {
return [...this.entries.keys()].filter((key) => this.get(key) !== undefined);
}
}
const cache = new ExpiringCache<number>();
cache.set("answer", 42, 60_000);
cache.set("score", 95, 60_000);
console.log(cache.get("answer"));
console.log(cache.keys());اكتب هنا