typescriptadvanced
TypeScript Generic LRU Cache
High-performance O(1) doubly linked LRU eviction cache
By ApeType Staff·42 lines·910 characters·1,420 total attempts
interface CacheNode<K, V> {
key: K;
value: V;
prev?: CacheNode<K, V>;
next?: CacheNode<K, V>;
}
export class LRUCache<K, V> {
private capacity: number;
private map = new Map<K, CacheNode<K, V>>();
private head?: CacheNode<K, V>;
private tail?: CacheNode<K, V>;
constructor(capacity: number) {
this.capacity = capacity;
}
public get(key: K): V | undefined {
const node = this.map.get(key);
if (!node) return undefined;
this.detach(node);
this.attachHead(node);
return node.value;
}
private detach(node: CacheNode<K, V>): void {
if (node.prev) node.prev.next = node.next;
if (node.next) node.next.prev = node.prev;
if (this.head === node) this.head = node.next;
if (this.tail === node) this.tail = node.prev;
}
private attachHead(node: CacheNode<K, V>): void {
node.next = this.head;
node.prev = undefined;
if (this.head) this.head.prev = node;
this.head = node;
if (!this.tail) this.tail = node;
}
}
TRANSCRIBE
Ready when you are.
Test your muscle memory and transcription speed against this exact snippet.
Start Typing
Tip: Press Esc anytime to restart