Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created August 19, 2024 17:31
Show Gist options
  • Save aleclarson/1cb5095410eb110a3eb042969d62ab12 to your computer and use it in GitHub Desktop.
Save aleclarson/1cb5095410eb110a3eb042969d62ab12 to your computer and use it in GitHub Desktop.
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