Added more functionality to the Pokedex; WIP - add more testing and refactor
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
Reference in New Issue
Block a user