pokedex_cli/internal/pokecache/pokecache.go

64 lines
1.0 KiB
Go
Raw Permalink Normal View History

2025-10-04 17:29:20 +00:00
package pokecache
import (
"sync"
"time"
2025-10-04 17:29:20 +00:00
)
type cacheEntry struct {
createdAt time.Time
val []byte
2025-10-04 17:29:20 +00:00
}
type Cache struct {
PokeCache map[string]cacheEntry
Interval time.Duration
Mu sync.Mutex
2025-10-04 17:29:20 +00:00
}
func (c *Cache) Add(key string, val []byte) {
newEntry := cacheEntry{
createdAt: time.Now(),
val: val,
2025-10-04 17:29:20 +00:00
}
c.Mu.Lock()
defer c.Mu.Unlock()
c.PokeCache[key] = newEntry
}
func (c *Cache) Get(key string) ([]byte, bool) {
c.Mu.Lock()
defer c.Mu.Unlock()
cache, exists := c.PokeCache[key]
if !exists {
return nil, false
}
return cache.val, true
}
func (c *Cache) reapLoop() {
ticker := time.NewTicker(c.Interval)
defer ticker.Stop()
for range ticker.C {
c.Mu.Lock()
for k, v := range c.PokeCache {
if time.Since(v.createdAt) > c.Interval {
delete(c.PokeCache, k)
2025-10-04 17:29:20 +00:00
}
}
c.Mu.Unlock()
}
}
func NewCache(interval time.Duration) *Cache {
newCache := Cache{
PokeCache: map[string]cacheEntry{},
Interval: interval,
Mu: sync.Mutex{},
2025-10-04 17:29:20 +00:00
}
go newCache.reapLoop()
return &newCache
}