From 08eaea92d177c0df1b192c2e4781af47da8aec3b Mon Sep 17 00:00:00 2001 From: William Perron Date: Tue, 20 Feb 2024 10:41:21 -0500 Subject: [PATCH] add keys to values --- sieve.go | 19 ++++++++++++++----- sieve_test.go | 30 ++++++++++++++++++++---------- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/sieve.go b/sieve.go index 43561c7..3f0a86c 100644 --- a/sieve.go +++ b/sieve.go @@ -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 } } diff --git a/sieve_test.go b/sieve_test.go index 0e3503c..fafea7b 100644 --- a/sieve_test.go +++ b/sieve_test.go @@ -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 }) }