Skip to content

Commit

Permalink
Feat: add maps filter (#79)
Browse files Browse the repository at this point in the history
Signed-off-by: Yin Da <yd219913@alibaba-inc.com>
Co-authored-by: Tianxin Dong <dongtianxin.tx@alibaba-inc.com>
  • Loading branch information
Somefive and FogDong committed May 18, 2023
1 parent 841accb commit 7648e2b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
11 changes: 11 additions & 0 deletions util/maps/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ func Map[K comparable, U any, V any](m map[K]U, fn func(U) V) map[K]V {
return _m
}

// Filter functional filter for map items
func Filter[K comparable, V any](m map[K]V, fn func(K, V) bool) map[K]V {
_m := make(map[K]V, len(m))
for key, val := range m {
if fn(key, val) {
_m[key] = val
}
}
return _m
}

// Copy return a copy of given map
func Copy[K comparable, V any](m map[K]V) map[K]V {
_m := make(map[K]V)
Expand Down
4 changes: 4 additions & 0 deletions util/maps/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,8 @@ func TestUtils(t *testing.T) {

_m := maps.Copy(m)
require.Equal(t, 2, len(_m))

_m = maps.Filter(m, func(k string, _ int) bool { return k == "a" })
_m = maps.Map(_m, func(v int) int { return v + 1 })
require.Equal(t, map[string]int{"a": 2}, _m)
}

0 comments on commit 7648e2b

Please sign in to comment.