@@ -3,7 +3,14 @@ export class Lru<K, V> {
33 private head : K | null = null ;
44 private tail : K | null = null ;
55
6- constructor ( private limit = 1000 ) { }
6+ constructor ( private limit = 1000 ) {
7+ // Normalize limit; fall back to sensible default (1000) to keep caching enabled
8+ let normalized = Number . isFinite ( this . limit )
9+ ? Math . floor ( this . limit )
10+ : 1000 ;
11+ if ( normalized <= 0 ) normalized = 1000 ;
12+ this . limit = normalized ;
13+ }
714
815 get ( key : K ) : V | undefined {
916 const node = this . map . get ( key ) ;
@@ -20,7 +27,10 @@ export class Lru<K, V> {
2027 return ;
2128 }
2229 node = { prev : null , next : this . head , value } ;
23- if ( this . head ) this . map . get ( this . head ) ! . prev = key ;
30+ if ( this . head ) {
31+ const headNode = this . map . get ( this . head ) ;
32+ if ( headNode ) headNode . prev = key ;
33+ }
2434 this . head = key ;
2535 if ( ! this . tail ) this . tail = key ;
2636 this . map . set ( key , node ) ;
@@ -31,23 +41,42 @@ export class Lru<K, V> {
3141 if ( this . head === key ) return ; // already MRU
3242
3343 // detach
34- if ( node . prev ) this . map . get ( node . prev ) ! . next = node . next ;
35- if ( node . next ) this . map . get ( node . next ) ! . prev = node . prev ;
44+ if ( node . prev ) {
45+ const prevNode = this . map . get ( node . prev ) ;
46+ if ( prevNode ) prevNode . next = node . next ;
47+ }
48+ if ( node . next ) {
49+ const nextNode = this . map . get ( node . next ) ;
50+ if ( nextNode ) nextNode . prev = node . prev ;
51+ }
3652 if ( this . tail === key ) this . tail = node . prev ;
3753
3854 // move to head
3955 node . prev = null ;
4056 node . next = this . head ;
41- if ( this . head ) this . map . get ( this . head ) ! . prev = key ;
57+ if ( this . head ) {
58+ const headNode = this . map . get ( this . head ) ;
59+ if ( headNode ) headNode . prev = key ;
60+ }
4261 this . head = key ;
4362 }
4463
4564 private evict ( ) {
4665 const old = this . tail ;
4766 if ( ! old ) return ;
48- const node = this . map . get ( old ) ! ;
49- if ( node . prev ) this . map . get ( node . prev ) ! . next = null ;
67+ const node = this . map . get ( old ) ;
68+ if ( ! node ) {
69+ // Tail pointer is stale; reset pointers conservatively
70+ if ( this . head === old ) this . head = null ;
71+ this . tail = null ;
72+ return ;
73+ }
74+ if ( node . prev ) {
75+ const prevNode = this . map . get ( node . prev ) ;
76+ if ( prevNode ) prevNode . next = null ;
77+ }
5078 this . tail = node . prev ;
79+ if ( this . head === old ) this . head = null ;
5180 this . map . delete ( old ) ;
5281 }
5382
0 commit comments