use ES6 Map if we can (#602)

This commit is contained in:
Jordi Bunster
2021-04-27 08:14:21 -07:00
committed by GitHub
parent 127784abdd
commit 5cf16d01b5
20 changed files with 106 additions and 478 deletions

View File

@@ -1,56 +1,27 @@
import { HashMap } from "./HashMap";
export class ObjectCache<T> extends HashMap<T> {
private keyQueue: string[]; // Last touched key FIFO to purge cache if too big.
private maxNbElements: number;
public constructor(maxNbElements: number) {
export class ObjectCache<T> extends Map<string, T> {
constructor(private limit: number) {
super();
this.keyQueue = [];
this.maxNbElements = maxNbElements;
this.clear();
}
public clear(): void {
super.clear();
this.keyQueue = [];
public get(key: string): T | undefined {
return this.touch(key);
}
public get(key: string): T {
this.markKeyAsTouched(key);
return super.get(key);
}
public set(key: string, value: T): void {
super.set(key, value);
this.markKeyAsTouched(key);
if (super.size() > this.maxNbElements && key !== this.keyQueue[0]) {
this.reduceCacheSize();
public set(key: string, value: T): this {
if (this.size === this.limit) {
this.delete(this.keys().next().value);
}
return this.touch(key, value), this;
}
/**
* Invalidate elements to keep the total number below the limit
*/
private reduceCacheSize(): void {
// remove a key
const oldKey = this.keyQueue.shift();
if (oldKey) {
super.delete(oldKey);
private touch(key: string, value = super.get(key)) {
// Map keeps (re) insertion order according to ES6 spec
if (value) {
this.delete(key);
super.set(key, value);
}
}
/**
* Bubble up this key as new.
* @param key
*/
private markKeyAsTouched(key: string) {
const n = this.keyQueue.indexOf(key);
if (n > -1) {
this.keyQueue.splice(n, 1);
}
this.keyQueue.push(key);
return value;
}
}