add keys to values

main
William Perron 9 months ago
parent 511bdc61c5
commit 08eaea92d1
Signed by: wperron
GPG Key ID: BFDB4EF72D73C5F2

@ -1,6 +1,7 @@
package sieve
type node struct {
key string
value string
visited bool
prev, next *node
@ -21,15 +22,15 @@ func NewCache(cap int) *SieveCache {
}
// Access touches the item `v` in the cache
func (sc *SieveCache) Access(v string) {
if n, ok := sc.cache[v]; ok {
func (sc *SieveCache) Put(k, v string) {
if n, ok := sc.cache[k]; ok {
n.visited = true
} else {
if sc.size == sc.cap {
sc.evict()
}
newNode := &node{value: v}
newNode := &node{key: k, value: v}
sc.addToHead(newNode)
sc.cache[v] = newNode
sc.size += 1
@ -37,13 +38,21 @@ func (sc *SieveCache) Access(v string) {
}
}
func (sc *SieveCache) Get(k string) string {
if n, ok := sc.cache[k]; ok {
n.visited = true
return n.value
}
return ""
}
// Range iterates over the values in the cache, stops the iteration if the
// closure returns false.
func (sc *SieveCache) Range(f func(v string) bool) {
func (sc *SieveCache) Range(f func(k, v string) bool) {
current := sc.head
keepGoing := true
for current != nil && keepGoing {
keepGoing = f(current.value)
keepGoing = f(current.key, current.value)
current = current.next
}
}

@ -1,18 +1,28 @@
package sieve
import "testing"
import (
"slices"
"testing"
)
func TestSieveCache(t *testing.T) {
cache := NewCache(3)
cache.Access("A")
cache.Access("B")
cache.Access("C")
cache.Access("D")
cache.Access("B")
cache.Access("E")
cache.Access("A")
cache.Range(func(v string) bool {
t.Log(v)
cache.Put("a", "A")
cache.Put("b", "B")
cache.Put("c", "C")
cache.Put("d", "D")
cache.Put("b", "B")
cache.Put("e", "E")
cache.Put("a", "A")
expectedKeys := []string{"a", "b", "e"}
count := 0
cache.Range(func(k, _ string) bool {
count++
if !slices.Contains(expectedKeys, k) {
t.Fail()
t.Errorf("unexpected key in result: %s", k)
}
return true
})
}

Loading…
Cancel
Save