Skip to content

Commit 22fcfc4

Browse files
fix(TTLCache): reset insertion order on key update in set() [ GSSOC '26 ] (JhaSourav07#598)
* fix(TTLCache): reset insertion order on key update in set() * ci: retrigger pipeline
1 parent 1131594 commit 22fcfc4

1 file changed

Lines changed: 6 additions & 4 deletions

File tree

lib/cache.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,19 +90,21 @@ export class TTLCache<T> {
9090
* cache.set("user:1",userData,5000);
9191
*/
9292
set(key: string, value: T, ttlMs: number): void {
93-
// Capacity eviction (FIFO / LRU-lite)
93+
if (ttlMs <= 0) throw new RangeError(`ttlMs must be positive, got ${ttlMs}`);
94+
9495
const maxSize = this.maxSize;
9596
if (maxSize !== undefined && this.store.size >= maxSize && !this.store.has(key)) {
96-
this.sweep(); // Remove expired entries first to free up capacity
97+
this.sweep();
9798
if (this.store.size >= maxSize) {
98-
// Find the oldest item (first inserted) and remove it
99-
const oldestKey = this.store.keys().next().value;
99+
const oldestKey = this.store.keys().next().value as string | undefined;
100100
if (oldestKey !== undefined) {
101101
this.store.delete(oldestKey);
102102
}
103103
}
104104
}
105105

106+
// Fix: delete first so updated keys move to end (newest position)
107+
this.store.delete(key);
106108
this.store.set(key, { value, expiresAt: Date.now() + ttlMs });
107109
}
108110

0 commit comments

Comments
 (0)