Added more functionality to the Pokedex; WIP - add more testing and refactor

This commit is contained in:
V
2025-10-05 15:00:38 +01:00
parent f0b303c0c0
commit f6e8038cdc
14 changed files with 324 additions and 86 deletions
+11 -13
View File
@@ -1,25 +1,25 @@
package pokecache
import (
"time"
"sync"
"time"
)
type cacheEntry struct {
createdAt time.Time
val []byte
createdAt time.Time
val []byte
}
type Cache struct {
PokeCache map[string]cacheEntry
Interval time.Duration
Mu sync.Mutex
PokeCache map[string]cacheEntry
Interval time.Duration
Mu sync.Mutex
}
func (c *Cache) Add(key string, val []byte) {
newEntry := cacheEntry{
createdAt: time.Now(),
val: val,
createdAt: time.Now(),
val: val,
}
c.Mu.Lock()
defer c.Mu.Unlock()
@@ -45,7 +45,7 @@ func (c *Cache) reapLoop() {
c.Mu.Lock()
for k, v := range c.PokeCache {
if time.Since(v.createdAt) > c.Interval {
delete(c.PokeCache, k)
delete(c.PokeCache, k)
}
}
c.Mu.Unlock()
@@ -55,11 +55,9 @@ func (c *Cache) reapLoop() {
func NewCache(interval time.Duration) *Cache {
newCache := Cache{
PokeCache: map[string]cacheEntry{},
Interval: interval,
Mu: sync.Mutex{},
Interval: interval,
Mu: sync.Mutex{},
}
go newCache.reapLoop()
return &newCache
}
+2 -3
View File
@@ -1,12 +1,11 @@
package pokecache
import (
"fmt"
"testing"
"time"
"fmt"
)
func TestAddGet(t *testing.T) {
const interval = 5 * time.Second
cases := []struct {
@@ -54,7 +53,7 @@ func TestReapLoop(t *testing.T) {
const waitTime = baseTime + 5*time.Millisecond
cache := NewCache(baseTime)
cache.Add("https://example.com", []byte("testdata"))
_, ok := cache.Get("https://example.com")
if !ok {
t.Errorf("expected to find key")