mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-13 09:12:28 +08:00
feat: add Filter func
This commit is contained in:
@@ -45,3 +45,15 @@ func ForEach[K comparable, V any](m map[K]V, iteratee func(key K, value V)) {
|
|||||||
iteratee(k, v)
|
iteratee(k, v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Filter iterates over map, return a new map contains all key and value pairs pass the predicate function
|
||||||
|
func Filter[K comparable, V any](m map[K]V, predicate func(key K, value V) bool) map[K]V {
|
||||||
|
res := make(map[K]V)
|
||||||
|
|
||||||
|
for k, v := range m {
|
||||||
|
if predicate(k, v) {
|
||||||
|
res[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|||||||
@@ -81,3 +81,25 @@ func TestForEach(t *testing.T) {
|
|||||||
|
|
||||||
assert.Equal(10, sum)
|
assert.Equal(10, sum)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFilter(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestFilter")
|
||||||
|
|
||||||
|
m := map[string]int{
|
||||||
|
"a": 1,
|
||||||
|
"b": 2,
|
||||||
|
"c": 3,
|
||||||
|
"d": 4,
|
||||||
|
"e": 5,
|
||||||
|
}
|
||||||
|
isEven := func(_ string, value int) bool {
|
||||||
|
return value%2 == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
acturl := Filter(m, isEven)
|
||||||
|
|
||||||
|
assert.Equal(map[string]int{
|
||||||
|
"b": 2,
|
||||||
|
"d": 4,
|
||||||
|
}, acturl)
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user