Added filter function

This commit is contained in:
Eduard Urbach 2023-07-06 23:46:47 +02:00
parent c3e12a7663
commit 038b6fa31f
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
2 changed files with 43 additions and 1 deletions

View File

@ -13,6 +13,7 @@ type Collection[T any] interface {
Clear()
Delete(key string)
Exists(key string) bool
Filter(func(*T) bool) <-chan *T
Get(key string) (value *T, err error)
Set(key string, value *T)
}
@ -66,6 +67,25 @@ func (c *collection[T]) All() <-chan *T {
return channel
}
// Filter returns a channel of all objects that pass the given filter function.
func (c *collection[T]) Filter(filter func(*T) bool) <-chan *T {
channel := make(chan *T)
go func() {
c.data.Range(func(key, value any) bool {
if filter(value.(*T)) {
channel <- value.(*T)
}
return true
})
close(channel)
}()
return channel
}
// Get returns the value for the given key.
func (c *collection[T]) Get(key string) (*T, error) {
value, exists := c.data.Load(key)

View File

@ -19,13 +19,35 @@ func TestAll(t *testing.T) {
users.Set("1", &User{Name: "User 1"})
users.Set("2", &User{Name: "User 2"})
users.Set("3", &User{Name: "User 3"})
count := 0
for range users.All() {
count++
}
assert.Equal(t, count, 2)
assert.Equal(t, count, 3)
}
func TestFilter(t *testing.T) {
users, err := ocean.New[User]("test")
assert.Nil(t, err)
defer users.Clear()
users.Set("1", &User{Name: "User 1"})
users.Set("2", &User{Name: "User 2"})
users.Set("3", &User{Name: "User 3"})
count := 0
f := func(user *User) bool {
return user.Name == "User 2"
}
for range users.Filter(f) {
count++
}
assert.Equal(t, count, 1)
}
func TestGet(t *testing.T) {