fix: lru map doesn't update links

closes #8
This commit is contained in:
alina 🌸 2023-09-18 19:40:09 +03:00
parent 53b008f8bc
commit 80d4c59c69
Signed by: teidesu
SSH key fingerprint: SHA256:uNeCpw6aTSU4aIObXLvHfLkDa82HWH9EiOj9AXOIRpI

View file

@ -96,6 +96,22 @@ export class LruMap<K extends string | number, V> {
return this._has(key) return this._has(key)
} }
private _remove(item: TwoWayLinkedList<K, V>): void {
if (item.p) {
this._last = item.p
this._last.n = undefined
} else {
// exhausted
this._last = undefined
this._first = undefined
}
// remove strong refs to and from the item
item.p = item.n = undefined
this._del(item.k)
this._size -= 1
}
set(key: K, value: V): void { set(key: K, value: V): void {
let item = this._get(key) let item = this._get(key)
@ -110,6 +126,9 @@ export class LruMap<K extends string | number, V> {
item = { item = {
k: key, k: key,
v: value, v: value,
// for jit to optimize stuff
n: undefined,
p: undefined,
} }
this._set(key, item as any) this._set(key, item as any)
@ -129,24 +148,13 @@ export class LruMap<K extends string | number, V> {
const oldest = this._last const oldest = this._last
if (oldest) { if (oldest) {
if (oldest.p) { this._remove(oldest)
this._last = oldest.p
this._last.n = undefined
} else {
// exhausted
this._last = undefined
this._first = undefined
}
// remove strong refs to and from the item
oldest.p = oldest.n = undefined
this._del(oldest.k)
this._size -= 1
} }
} }
} }
delete(key: K): void { delete(key: K): void {
this._del(key) const item = this._get(key)
if (item) this._remove(item)
} }
} }