@@ -455,6 +455,29 @@ export class LinkedMap<K, V> implements Map<K, V> {
455
455
this . _state ++ ;
456
456
}
457
457
458
+ protected trimNew ( newSize : number ) {
459
+ if ( newSize >= this . size ) {
460
+ return ;
461
+ }
462
+ if ( newSize === 0 ) {
463
+ this . clear ( ) ;
464
+ return ;
465
+ }
466
+ let current = this . _tail ;
467
+ let currentSize = this . size ;
468
+ while ( current && currentSize > newSize ) {
469
+ this . _map . delete ( current . key ) ;
470
+ current = current . previous ;
471
+ currentSize -- ;
472
+ }
473
+ this . _tail = current ;
474
+ this . _size = currentSize ;
475
+ if ( current ) {
476
+ current . next = undefined ;
477
+ }
478
+ this . _state ++ ;
479
+ }
480
+
458
481
private addItemFirst ( item : Item < K , V > ) : void {
459
482
// First time Insert
460
483
if ( ! this . _head && ! this . _tail ) {
@@ -601,10 +624,10 @@ export class LinkedMap<K, V> implements Map<K, V> {
601
624
}
602
625
}
603
626
604
- export class LRUCache < K , V > extends LinkedMap < K , V > {
627
+ abstract class Cache < K , V > extends LinkedMap < K , V > {
605
628
606
- private _limit : number ;
607
- private _ratio : number ;
629
+ protected _limit : number ;
630
+ protected _ratio : number ;
608
631
609
632
constructor ( limit : number , ratio : number = 1 ) {
610
633
super ( ) ;
@@ -640,15 +663,53 @@ export class LRUCache<K, V> extends LinkedMap<K, V> {
640
663
641
664
override set ( key : K , value : V ) : this {
642
665
super . set ( key , value , Touch . AsNew ) ;
643
- this . checkTrim ( ) ;
644
666
return this ;
645
667
}
646
668
647
- private checkTrim ( ) {
669
+ protected checkTrim ( ) {
648
670
if ( this . size > this . _limit ) {
649
- this . trimOld ( Math . round ( this . _limit * this . _ratio ) ) ;
671
+ this . trim ( Math . round ( this . _limit * this . _ratio ) ) ;
650
672
}
651
673
}
674
+
675
+ protected abstract trim ( newSize : number ) : void ;
676
+ }
677
+
678
+ export class LRUCache < K , V > extends Cache < K , V > {
679
+
680
+ constructor ( limit : number , ratio : number = 1 ) {
681
+ super ( limit , ratio ) ;
682
+ }
683
+
684
+ protected override trim ( newSize : number ) {
685
+ this . trimOld ( newSize ) ;
686
+ }
687
+
688
+ override set ( key : K , value : V ) : this {
689
+ super . set ( key , value ) ;
690
+ this . checkTrim ( ) ;
691
+ return this ;
692
+ }
693
+ }
694
+
695
+ export class MRUCache < K , V > extends Cache < K , V > {
696
+
697
+ constructor ( limit : number , ratio : number = 1 ) {
698
+ super ( limit , ratio ) ;
699
+ }
700
+
701
+ protected override trim ( newSize : number ) {
702
+ this . trimNew ( newSize ) ;
703
+ }
704
+
705
+ override set ( key : K , value : V ) : this {
706
+ if ( ! this . has ( key ) ) {
707
+ this . trim ( Math . round ( this . _limit * this . _ratio ) - 1 ) ;
708
+ }
709
+
710
+ super . set ( key , value ) ;
711
+ return this ;
712
+ }
652
713
}
653
714
654
715
export class CounterSet < T > {
0 commit comments