docs/.vitepress/theme/composables/search/lru-cache.ts
35 lines · 728 bytes
1export class LRUCache<K, V> {
2 private max: number
3 private cache: Map<K, V>
4
5 constructor(max: number = 10) {
6 this.max = max
7 this.cache = new Map<K, V>()
8 }
9
10 get(key: K): V | undefined {
11 let item = this.cache.get(key)
12 if (item !== undefined) {
13 // refresh key
14 this.cache.delete(key)
15 this.cache.set(key, item)
16 }
17 return item
18 }
19
20 set(key: K, val: V): void {
21 // refresh key
22 if (this.cache.has(key)) this.cache.delete(key)
23 // evict oldest
24 else if (this.cache.size === this.max) this.cache.delete(this.first()!)
25 this.cache.set(key, val)
26 }
27
28 first(): K | undefined {
29 return this.cache.keys().next().value
30 }
31
32 clear(): void {
33 this.cache.clear()
34 }
35}