Skip to content

Commit 62e4388

Browse files
committed
Add MRUCache type
1 parent b8b1731 commit 62e4388

File tree

1 file changed

+67
-6
lines changed

1 file changed

+67
-6
lines changed

src/vs/base/common/map.ts

Lines changed: 67 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,29 @@ export class LinkedMap<K, V> implements Map<K, V> {
455455
this._state++;
456456
}
457457

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+
458481
private addItemFirst(item: Item<K, V>): void {
459482
// First time Insert
460483
if (!this._head && !this._tail) {
@@ -601,10 +624,10 @@ export class LinkedMap<K, V> implements Map<K, V> {
601624
}
602625
}
603626

604-
export class LRUCache<K, V> extends LinkedMap<K, V> {
627+
abstract class Cache<K, V> extends LinkedMap<K, V> {
605628

606-
private _limit: number;
607-
private _ratio: number;
629+
protected _limit: number;
630+
protected _ratio: number;
608631

609632
constructor(limit: number, ratio: number = 1) {
610633
super();
@@ -640,15 +663,53 @@ export class LRUCache<K, V> extends LinkedMap<K, V> {
640663

641664
override set(key: K, value: V): this {
642665
super.set(key, value, Touch.AsNew);
643-
this.checkTrim();
644666
return this;
645667
}
646668

647-
private checkTrim() {
669+
protected checkTrim() {
648670
if (this.size > this._limit) {
649-
this.trimOld(Math.round(this._limit * this._ratio));
671+
this.trim(Math.round(this._limit * this._ratio));
650672
}
651673
}
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+
}
652713
}
653714

654715
export class CounterSet<T> {

0 commit comments

Comments
 (0)