Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions Javascript/cache algorithm/lru.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
class Node {
constructor(key, value, expiry) {
this.key = key;
this.value = value;
this.expiry = expiry;
this.prev = null;
this.next = null;
}
}

export class LRUCache {
constructor({ max = 100, ttl = 0 } = {}) {
this.max = max;
this.ttl = ttl;
this.map = new Map();

// Dummy head and tail (avoid edge checks)
this.head = new Node(null, null, null);
this.tail = new Node(null, null, null);

this.head.next = this.tail;
this.tail.prev = this.head;
}

_addNode(node) {
node.prev = this.head;
node.next = this.head.next;

this.head.next.prev = node;
this.head.next = node;
}

_removeNode(node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}

_moveToFront(node) {
this._removeNode(node);
this._addNode(node);
}

_removeLRU() {
const lru = this.tail.prev;
if (lru === this.head) return;

this._removeNode(lru);
this.map.delete(lru.key);
}

_isExpired(node) {
return this.ttl > 0 && Date.now() > node.expiry;
}

get(key) {
const node = this.map.get(key);
if (!node) return null;

if (this._isExpired(node)) {
this._removeNode(node);
this.map.delete(key);
return null;
}

this._moveToFront(node);
return node.value;
}

set(key, value) {
let node = this.map.get(key);
const expiry = this.ttl > 0 ? Date.now() + this.ttl : Infinity;

if (node) {
node.value = value;
node.expiry = expiry;
this._moveToFront(node);
return;
}

node = new Node(key, value, expiry);
this.map.set(key, node);
this._addNode(node);

if (this.map.size > this.max) {
this._removeLRU();
}
}

delete(key) {
const node = this.map.get(key);
if (!node) return false;

this._removeNode(node);
return this.map.delete(key);
}

clear() {
this.map.clear();
this.head.next = this.tail;
this.tail.prev = this.head;
}

size() {
return this.map.size;
}
}