summaryrefslogtreecommitdiff
path: root/shared/utils/src/lru-map.ts
blob: 79eb41cb678bc344e4d61774ef2810c8d77eae97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 * LRU Map implementation storing key/values up to a provided size limit. Beyond that
 * size limit, the least recently used entry is evicted.
 *
 * @see https://github.pie.apple.com/isao/lru-map
 */
export class LruMap<K, V> extends Map<K, V> {
    private sizeLimit: number;

    constructor(sizeLimit: number) {
        super();
        this.setSizeLimit(sizeLimit);
        // Needed to convince TS that this is set (it's actually handled by setSizeLimit)
        this.sizeLimit = sizeLimit;
    }

    /**
     * Retrieve a value from the map with a given key.
     * @param key The key for the entry
     * @return value The entry's value (or undefined if non existent)
     */
    get(key: K): V | undefined {
        let value: V | undefined;

        if (this.has(key)) {
            value = super.get(key);

            // Map entries are always in insertion order. So
            // readding, pushes this entry to the top of the LRU.
            this.delete(key);
            super.set(key, value!);
        }

        return value;
    }

    set(key: K, value: V): this {
        super.set(key, value);
        this.prune();
        return this;
    }

    setSizeLimit(newSizeLimit: number): void {
        if (newSizeLimit < 0 || !isFinite(newSizeLimit)) {
            throw new Error(
                `setSizeLimit expects finite positive number, got: ${newSizeLimit}`,
            );
        }

        this.sizeLimit = newSizeLimit;
        this.prune();
    }

    private prune(): void {
        while (this.size > this.sizeLimit) {
            const leastRecentlyUsedKey = this.keys().next().value;
            this.delete(leastRecentlyUsedKey);
        }
    }
}