LRU cache backed by map and container/list
Go
package lru
import "container/list"
// Cache is a bounded LRU map; the front of order is most recently used.
type Cache struct {
cap int
order *list.List
items map[string]*list.Element // element value: [2]any{key, value}
}
// New returns a Cache that keeps at most capacity entries.
func New(capacity int) *Cache {
return &Cache{cap: max(capacity, 1), order: list.New(), items: map[string]*list.Element{}}
}
// Get reports the value for key and marks it as most recently used.
func (c *Cache) Get(key string) (any, bool) {
if el, ok := c.items[key]; ok {
c.order.MoveToFront(el)
return el.Value.([2]any)[1], true
}
return nil, false
}
// Put stores value under key and evicts the least recently used entry.
func (c *Cache) Put(key string, value any) {
if el, ok := c.items[key]; ok {
el.Value = [2]any{key, value}
c.order.MoveToFront(el)
return
}
c.items[key] = c.order.PushFront([2]any{key, value})
if c.order.Len() > c.cap {
old := c.order.Back()
c.order.Remove(old)
delete(c.items, old.Value.([2]any)[0].(string))
}
}