JAVASCRIPT
LRU Cache - Least Recently Used
تنفيذ كامل لـ LRU Cache باستخدام Map وDoubly Linked List. كفاءة O(1) لجميع العمليات.
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
}
get(key) {
if (!this.cache.has(key)) return -1;
// Move to end (most recently used)
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
put(key, value) {
if (this.cache.has(key)) {
// Update existing
this.cache.delete(key);
} else if (this.cache.size >= this.capacity) {
// Remove least recently used (first item)
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, value);
}
// Advanced: With TTL (Time To Live)
setWithTTL(key, value, ttl) {
this.put(key, {
value,
expiresAt: Date.now() + ttl
});
}
getWithTTL(key) {
const item = this.get(key);
if (item === -1) return -1;
if (item.expiresAt && Date.now() > item.expiresAt) {
this.cache.delete(key);
return -1;
}
return item.value || item;
}
}
// Usage
const cache = new LRUCache(3);
cache.put(1, 'a');
cache.put(2, 'b');
cache.put(3, 'c');
cache.get(1); // Moves 1 to end
cache.put(4, 'd'); // Removes 2 (LRU)
💡 مثال الاستخدام
استخدم LRU Cache لتحسين أداء التطبيقات، تخزين مؤقت ذكي، أو إدارة الذاكرة بكفاءة.
استخدام حر
هذا الكود متاح للاستخدام الحر. إذا كان لديك أسئلة أو تحتاج مساعدة، لا تتردد في التواصل معي.