export class SwappingLru {
    constructor(maxSize) {
        this.cacheA = new Map();
        this.cacheB = new Map();
        this.hits = 0;
        this.misses = 0;
        this.resets = 0;
        this.clears = 0;
        this._lastCheckedAt = -1;
        this.maxSize = maxSize;
    }
    get(id) {
        const cacheA = this.cacheA.get(id);
        if (cacheA) {
            this.hits++;
            return cacheA;
        }
        const cacheB = this.cacheB.get(id);
        if (cacheB == null) {
            this.misses++;
            return null;
        }
        this.hits++;
        // If a object is still useful move it into the main cache
        this.cacheA.set(id, cacheB);
        this.cacheB.delete(id);
        return cacheB;
    }
    /** Reset the cache */
    clear() {
        this.cacheA.clear();
        this.cacheB.clear();
        this.clears++;
    }
    set(id, tiff) {
        this.cacheA.set(id, tiff);
        this.check();
    }
    /** Validate the size of the cache has not exploded */
    check() {
        this._lastCheckedAt = Date.now();
        if (this.maxSize <= 0)
            return;
        if (this.currentSize <= this.maxSize)
            return;
        this.resets++;
        // Paranoia if we are resetting too often something is wrong, reset the entire cache.
        if (this.resets > 100) {
            this.resets = 0;
            return this.clear();
        }
        this.cacheB = this.cacheA;
        this.cacheA = new Map();
    }
    /** Calculate the total number of bytes used by this cache */
    get currentSize() {
        let size = 0;
        for (const value of this.cacheA.values())
            size += value.size;
        return size;
    }
}
//# sourceMappingURL=swapping.lru.js.map