1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add FindValuesBy

This commit is contained in:
dudaodong
2025-04-01 11:35:24 +08:00
parent 3849337919
commit ceb706b874
5 changed files with 154 additions and 5 deletions

View File

@@ -666,3 +666,17 @@ func GetOrDefault[K comparable, V any](m map[K]V, key K, defaultValue V) V {
}
return defaultValue
}
// FindValuesBy returns a slice of values from the map that satisfy the given predicate function.
// Play: todo
func FindValuesBy[K comparable, V any](m map[K]V, predicate func(key K, value V) bool) []V {
result := make([]V, 0)
for k, v := range m {
if predicate(k, v) {
result = append(result, v)
}
}
return result
}

View File

@@ -829,3 +829,21 @@ func ExampleOrderedMap_UnmarshalJSON() {
// fmt.Println(om.Elements())
}
func ExampleFindValuesBy() {
m := map[int]string{
1: "a",
2: "b",
3: "c",
4: "d",
}
result := FindValuesBy(m, func(k int, v string) bool {
return k%2 == 0
})
fmt.Println(result)
// Output:
// [b d]
}

View File

@@ -888,3 +888,41 @@ func TestGetOrDefault(t *testing.T) {
result2 := GetOrDefault(m1, 5, "123")
assert.Equal("123", result2)
}
func TestFindValuesBy(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestFindValuesBy")
tests := []struct {
name string
inputMap map[string]string
key string
expected []string
}{
{
name: "Key exists",
inputMap: map[string]string{"a": "1", "b": "2", "c": "3"},
key: "b",
expected: []string{"2"},
},
{
name: "Key does not exist",
inputMap: map[string]string{"a": "1", "b": "2", "c": "3"},
key: "d",
expected: []string{},
},
{
name: "Empty map",
inputMap: map[string]string{},
key: "a",
expected: []string{},
},
}
for _, tt := range tests {
result := FindValuesBy(tt.inputMap, func(key string, value string) bool {
return key == tt.key
})
assert.Equal(tt.expected, result)
}
}