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

@ -1,18 +1,28 @@
package sieve package sieve
import "testing" import (
"slices"
"testing"
)
func TestSieveCache(t *testing.T) { func TestSieveCache(t *testing.T) {
cache := NewCache(3) cache := NewCache(3)
cache.Access("A") cache.Put("a", "A")
cache.Access("B") cache.Put("b", "B")
cache.Access("C") cache.Put("c", "C")
cache.Access("D") cache.Put("d", "D")
cache.Access("B") cache.Put("b", "B")
cache.Access("E") cache.Put("e", "E")
cache.Access("A") cache.Put("a", "A")
cache.Range(func(v string) bool {
t.Log(v) 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 return true
}) })
} }

Loading…
Cancel
Save