File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments