-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlruCache.ts
66 lines (50 loc) · 1.67 KB
/
lruCache.ts
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
61
62
63
64
65
66
import {CacheProvider} from './cacheProvider';
/**
* In-memory Least Recently Used (LRU) cache.
*/
export class LruCache<T = any> implements CacheProvider<string, T> {
private cache = new Map<string, T>();
private readonly capacity: number;
private constructor(capacity: number) {
this.capacity = capacity;
}
/**
* Initializes a new instance with the given capacity.
*
* @param {number} capacity The maximum number of entries in the cache. Must be a
* positive safe integer.
*/
public static ofCapacity(capacity: number): LruCache {
if (!Number.isSafeInteger(capacity) || capacity < 1) {
throw new Error('LRU capacity must be a positive safe integer.');
}
return new this(capacity);
}
public get(key: string, loader: (key: string) => Promise<T>): Promise<T> {
if (!this.cache.has(key)) {
return loader(key);
}
const value = this.cache.get(key)!;
// Reposition the key as the most recently used value
this.cache.delete(key);
this.cache.set(key, value);
return Promise.resolve(value);
}
public set(key: string, value: T): Promise<void> {
this.cache.set(key, value);
this.prune();
return Promise.resolve();
}
public delete(key: string): Promise<void> {
this.cache.delete(key);
return Promise.resolve();
}
private prune(): void {
while (this.cache.size > this.capacity) {
const leastRecentlyUsedKey = this.cache
.keys()
.next();
this.cache.delete(leastRecentlyUsedKey.value);
}
}
}