// Exercise 05 — LRU Cache // // ASSIGNMENT // ---------- // Implement a thread-safe LRU cache: // // 1. NewLRU(capacity): holds at most `capacity` entries. // 2. Get(key): returns (value, true) and marks the entry most-recently-used; // (nil, false) on miss. // 3. Put(key, value): inserts or updates; updating also marks MRU. // When over capacity, evicts the LEAST recently used entry. // 4. Both operations O(1). (Hint: map + container/list, or hand-roll a // doubly linked list.) // 5. Safe for concurrent use (tests run with -race). // // Run the tests: go test -race ./05-lru-cache/ package main import "fmt" type LRU struct { // TODO: fields (mutex, capacity, map[string]*list.Element, *list.List) // Remember: the list element must store the KEY too, or you can't // delete the map entry on eviction. } // NewLRU creates an LRU cache with the given capacity (capacity >= 1). // TODO: implement me. func NewLRU(capacity int) *LRU { return &LRU{} } // Get returns the value and whether it was present. Hit = mark MRU. // TODO: implement me. func (c *LRU) Get(key string) (any, bool) { return nil, false } // Put inserts/updates a value, evicting the LRU entry if over capacity. // TODO: implement me. func (c *LRU) Put(key string, val any) { } // Len returns the current number of entries. // TODO: implement me. func (c *LRU) Len() int { return 0 } func main() { c := NewLRU(2) c.Put("a", 1) c.Put("b", 2) c.Get("a") // a is now MRU c.Put("c", 3) // evicts b _, ok := c.Get("b") fmt.Println("b present:", ok) // false }