Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#44] Add DeleteByFunc function #45

Merged
merged 1 commit into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ func (bs baseCache[K, V]) Delete(key K) {
bs.cache.Delete(key)
}

// DeleteByFunc removes the association for this key from the cache when the given function returns true.
func (bs baseCache[K, V]) DeleteByFunc(f func(key K, value V) bool) {
bs.cache.DeleteByFunc(f)
}

// Range iterates over all items in the cache.
//
// Iteration stops early when the given function returns false.
Expand Down
23 changes: 23 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,29 @@ func TestCache_SetWithTTL(t *testing.T) {
}
}

func TestBaseCache_DeleteByFunc(t *testing.T) {
size := 256
c, err := MustBuilder[int, int](size).WithTTL(time.Hour).Build()
if err != nil {
t.Fatalf("can not create builder: %v", err)
}

for i := 0; i < size; i++ {
c.Set(i, i)
}

c.DeleteByFunc(func(key int, value int) bool {
return key%2 == 1
})

c.Range(func(key int, value int) bool {
if key%2 == 1 {
t.Fatalf("key should be odd, but got: %d", key)
}
return true
})
}

func TestCache_Ratio(t *testing.T) {
c, err := MustBuilder[uint64, uint64](100).CollectStats().Build()
if err != nil {
Expand Down
16 changes: 16 additions & 0 deletions internal/core/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,22 @@ func (c *Cache[K, V]) Delete(key K) {
}
}

// DeleteByFunc removes the association for this key from the cache when the given function returns true.
func (c *Cache[K, V]) DeleteByFunc(f func(key K, value V) bool) {
// TODO(maypok86): This function can be implemented more efficiently, if the performance of this implementation is not enough for you, then come with an issue :)
var keysToDelete []K
c.Range(func(key K, value V) bool {
if f(key, value) {
keysToDelete = append(keysToDelete, key)
}
return true
})

for _, key := range keysToDelete {
c.Delete(key)
}
}

func (c *Cache[K, V]) cleanup() {
expired := make([]*node.Node[K, V], 0, 128)
for {
Expand Down
Loading