* init Signed-off-by: Innei <tukon479@gmail.com> * feat: grid Signed-off-by: Innei <tukon479@gmail.com> * refactor: mark read logci Signed-off-by: Innei <tukon479@gmail.com> * chore: remove react-virtuoso Signed-off-by: Innei <tukon479@gmail.com> * fix: video Signed-off-by: Innei <tukon479@gmail.com> * transition Signed-off-by: Innei <tukon479@gmail.com> * fix: image memo loaded status Signed-off-by: Innei <tukon479@gmail.com> * fix: sort button Signed-off-by: Innei <tukon479@gmail.com> * feat: cjk truncate Signed-off-by: Innei <tukon479@gmail.com> --------- Signed-off-by: Innei <tukon479@gmail.com>
58 lines
1.1 KiB
TypeScript
58 lines
1.1 KiB
TypeScript
export class LRUCache<K, V> {
|
|
private capacity: number
|
|
private cache: Map<K, V>
|
|
private keys: K[]
|
|
|
|
constructor(capacity: number) {
|
|
if (capacity <= 0) {
|
|
throw new Error("Capacity must be positive")
|
|
}
|
|
|
|
this.capacity = capacity
|
|
this.cache = new Map()
|
|
this.keys = []
|
|
}
|
|
|
|
get(key: K): V | undefined {
|
|
if (!this.cache.has(key)) {
|
|
return undefined
|
|
}
|
|
|
|
this.keys = this.keys.filter((k) => k !== key)
|
|
this.keys.push(key)
|
|
|
|
return this.cache.get(key)
|
|
}
|
|
|
|
put(key: K, value: V): void {
|
|
if (this.cache.has(key)) {
|
|
this.cache.set(key, value)
|
|
this.keys = this.keys.filter((k) => k !== key)
|
|
this.keys.push(key)
|
|
} else {
|
|
if (this.keys.length >= this.capacity) {
|
|
const leastUsedKey = this.keys.shift()
|
|
if (leastUsedKey !== undefined) {
|
|
this.cache.delete(leastUsedKey)
|
|
}
|
|
}
|
|
|
|
this.cache.set(key, value)
|
|
this.keys.push(key)
|
|
}
|
|
}
|
|
|
|
clear(): void {
|
|
this.cache.clear()
|
|
this.keys = []
|
|
}
|
|
|
|
size(): number {
|
|
return this.cache.size
|
|
}
|
|
|
|
getKeys(): K[] {
|
|
return [...this.keys]
|
|
}
|
|
}
|