Skip to content

Instantly share code, notes, and snippets.

@burdiuz
Last active November 28, 2021 07:29
Show Gist options
  • Save burdiuz/32f749eb123913608226001be1f73054 to your computer and use it in GitHub Desktop.
Save burdiuz/32f749eb123913608226001be1f73054 to your computer and use it in GitHub Desktop.
Simple Least Recently Used Cache implementation
const getNextIndex = (() => {
let index = 1;
const lastSafe = ((1 << 31) >>> 0) - 1;
return () => {
index += 1;
if (index >= lastSafe) {
index = 1;
}
return index;
};
})();
class LRUCache {
constructor(maxLength) {
this.map = new Map();
this.queue = new Queue();
this.currLength = 0;
this.maxLength = maxLength;
}
get length() {
return this.currLength;
}
get(id) {
const node = this.map.get(id);
return node && node.value;
}
put(value, id = getNextIndex()) {
let node = this.map.get(id);
if (node) {
node.value = value;
/*
1. remove node from current position
2. place it to the start(head) of the queue
*/
this.queue.enqueueNode(node);
return id;
}
node = this.queue.enqueue(value);
/*
with storing node in the map instead of value we don't need to
search for it when need to move/remove
*/
this.map.set(id, node);
this.currLength += 1;
if (this.currLength > this.maxLength) {
this.queue.dequeue();
}
return id;
}
remove(id) {
const node = this.map.get(id);
if (!node) {
return;
}
this.map.remove(id);
node.remove();
this.currLength -= 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment