docs/.vitepress/theme/composables/search/lru-cache.ts

e99483e755019aec16fad1233ee5b8aaebc1a79b
wotaku/docs/.vitepress/theme/composables/search/lru-cache.ts
taskylizard wotaku 2bea9706e6c 1 year ago

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}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form