Created
August 19, 2024 17:31
-
-
Save aleclarson/1cb5095410eb110a3eb042969d62ab12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class LeastRecentlyUsedCache<Key, Value> { | |
protected _capacity: number | |
protected _values: Map<Key, Value> | |
protected _timestamps: Map<Key, number> | |
constructor(capacity: number) { | |
this._capacity = capacity | |
this._values = new Map() | |
this._timestamps = new Map() | |
} | |
values() { | |
return Array.from(this._values) | |
} | |
has(key: Key) { | |
return this._values.has(key) | |
} | |
get(key: Key): Value | undefined { | |
if (this._values.has(key)) { | |
this._timestamps.set(key, Date.now()) | |
return this._values.get(key) | |
} | |
} | |
set(key: Key, value: Value): this { | |
this._values.set(key, value) | |
this._timestamps.set(key, Date.now()) | |
if (this._values.size > this._capacity) { | |
let oldestKey: Key | undefined | |
let oldestTimestamp = Infinity | |
for (const [key, timestamp] of this._timestamps) { | |
if (timestamp < oldestTimestamp) { | |
oldestKey = key | |
oldestTimestamp = timestamp | |
} | |
} | |
if (oldestKey) { | |
this._values.delete(oldestKey) | |
this._timestamps.delete(oldestKey) | |
} | |
} | |
return this | |
} | |
delete(key: Key): boolean { | |
return this._values.delete(key) && this._timestamps.delete(key) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment