Skip to content

Instantly share code, notes, and snippets.

@Sheraff
Created July 22, 2025 20:34
Show Gist options
  • Select an option

  • Save Sheraff/34b0f6eaf507833f6de851c954a0cb07 to your computer and use it in GitHub Desktop.

Select an option

Save Sheraff/34b0f6eaf507833f6de851c954a0cb07 to your computer and use it in GitHub Desktop.
LRU cache as a JS Map
class LRUMap<TKey, TValue> extends Map<TKey, TValue> {
constructor(max: number) {
super()
const get = this.get.bind(this)
const set = this.set.bind(this)
this.get = (key: TKey) => {
const item = get(key)
if (item !== undefined) {
// refresh key
this.delete(key)
set(key, item)
}
return item
}
this.set = (key: TKey, val: TValue) => {
// refresh key
if (this.has(key)) this.delete(key)
// evict oldest
else if (this.size == max) this.delete(this.keys().next().value!)
set(key, val)
return this
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment