Sure, here is a simple implementation of an LRU cache with time-based eviction in Go using generics:
package main
import (
"container/list"
"sync"
"time"
)
type CacheItem[T any] struct {
Value T
Time time.Time
}
type Cache[T any] struct {
maxSize int
items *list.List
timeEvict time.Duration
sync.RWMutex
}
func NewCache[T any](maxSize int, timeEvict time.Duration) *Cache[T] {
return &Cache[T]{
maxSize: maxSize,
items: list.New(),
timeEvict: timeEvict,
}
}
func (c *Cache[T]) Get(key int) (T, bool) {
c.Lock()
defer c.Unlock()
if c.items.Len() == 0 {
return T{}, false
}
for e := c.items.Front(); e != nil; e = e.Next() {
item := e.Value.(CacheItem[T])
if item.Value == key {
c.items.MoveToFront(e)
return item.Value, true
}
}
return T{}, false
}
func (c *Cache[T]) Put(key T) {
c.Lock()
defer c.Unlock()
if c.items.Len() == c.maxSize {
oldItem := c.items.Back()
c.items.Remove(oldItem)
}
c.items.PushFront(CacheItem[T]{
Value: key,
Time: time.Now(),
})
}
func (c *Cache[T]) EvictOldItems() {
c.Lock()
defer c.Unlock()
now := time.Now()
for e := c.items.Front(); e != nil; {
item := e.Value.(CacheItem[T])
if now.Sub(item.Time) > c.timeEvict {
e = e.Next()
c.items.Remove(e)
} else {
break
}
}
}
The Cache struct has a list of items, a maximum size and a duration for eviction. The Get method returns an item from the cache if it exists, otherwise returns a boolean false. The Put method adds an item to the cache and moves it to the front of the list. The EvictOldItems method removes items from the cache that are older than the specified duration.
The NewCache function creates a new instance of the cache with the specified maximum size and eviction duration. The CacheItem struct contains the value of the item and the time it was added to the cache.