File size: 1,413 Bytes
47b9de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from collections import OrderedDict


class CacheManager:
    """Simple cache manager with basic operations and LRU eviction."""
    
    def __init__(self, max_size=100):
        """Initialize cache with maximum size."""
        self.max_size = max_size
        self.cache = OrderedDict()
    
    def set(self, key, value):
        """Set a key-value pair in cache."""
        # If key exists, remove it first
        if key in self.cache:
            del self.cache[key]
        
        # If cache is full, remove oldest item
        if len(self.cache) >= self.max_size:
            self.cache.popitem(last=False)  # Remove first (oldest) item
        
        # Add new item
        self.cache[key] = value
    
    def get(self, key):
        """Get value by key. Returns None if not found."""
        if key in self.cache:
            # Move to end (mark as recently used)
            value = self.cache.pop(key)
            self.cache[key] = value
            return value
        return None
    
    def delete(self, key):
        """Delete a key from cache. Returns True if deleted, False if not found."""
        if key in self.cache:
            del self.cache[key]
            return True
        return False
    
    def clear(self):
        """Clear all items from cache."""
        self.cache.clear()
    
    def size(self):
        """Get current cache size."""
        return len(self.cache)