Skip to content

Instantly share code, notes, and snippets.

@oscarmarina
Created October 17, 2025 16:52
Show Gist options
  • Save oscarmarina/e56ebcb91cd4577d7be4b438dbe72469 to your computer and use it in GitHub Desktop.
Save oscarmarina/e56ebcb91cd4577d7be4b438dbe72469 to your computer and use it in GitHub Desktop.
LRU cache
export class LRUCache extends Map {
constructor(maxSize) {
if (maxSize <= 0) {
throw new Error('maxSize must be greater than 0');
}
super();
this.maxSize = maxSize;
}
set(key, value) {
super.delete(key);
super.set(key, value);
if (this.size > this.maxSize) {
const keyToDelete = this.keys().next().value;
if (keyToDelete !== undefined) {
this.delete(keyToDelete);
}
}
return this;
}
get(key) {
const value = super.get(key);
if (value !== undefined) {
// Deleting and setting the value again ensures the key is at the end of the LRU queue
this.delete(key);
this.set(key, value);
}
return value;
}
}
export class LRUCache<K, V> extends Map<K, V> {
constructor(public readonly maxSize: number) {
if (maxSize <= 0) {
throw new Error('maxSize must be greater than 0');
}
super();
}
override set(key: K, value: V): this {
super.delete(key);
super.set(key, value);
if (this.size > this.maxSize) {
const keyToDelete = this.keys().next().value;
if (keyToDelete !== undefined) {
this.delete(keyToDelete);
}
}
return this;
}
override get(key: K): V | undefined {
const value = super.get(key);
if (value !== undefined) {
// Deleting and setting the value again ensures the key is at the end of the LRU queue
this.delete(key);
this.set(key, value);
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment