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

feat: add FilterByValues function

This commit is contained in:
dudaodong
2023-02-17 11:59:44 +08:00
parent 4c1496b648
commit 2eb08f3404
2 changed files with 32 additions and 0 deletions

View File

@@ -110,6 +110,19 @@ func FilterByKeys[K comparable, V any](m map[K]V, keys []K) map[K]V {
return result return result
} }
// FilterByValues iterates over map, return a new map whose values are all given values.
// todo:
func FilterByValues[K comparable, V comparable](m map[K]V, values []V) map[K]V {
result := make(map[K]V)
for k, v := range m {
if slice.Contain(values, v) {
result[k] = v
}
}
return result
}
// Intersect iterates over maps, return a new map of key and value pairs in all given maps. // Intersect iterates over maps, return a new map of key and value pairs in all given maps.
// Play: https://go.dev/play/p/Zld0oj3sjcC // Play: https://go.dev/play/p/Zld0oj3sjcC
func Intersect[K comparable, V any](maps ...map[K]V) map[K]V { func Intersect[K comparable, V any](maps ...map[K]V) map[K]V {

View File

@@ -168,6 +168,25 @@ func TestFilterByKeys(t *testing.T) {
}, acturl) }, acturl)
} }
func TestFilterByValues(t *testing.T) {
assert := internal.NewAssert(t, "TestFilterByValues")
m := map[string]int{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
}
acturl := FilterByValues(m, []int{3, 4})
assert.Equal(map[string]int{
"c": 3,
"d": 4,
}, acturl)
}
func TestIntersect(t *testing.T) { func TestIntersect(t *testing.T) {
assert := internal.NewAssert(t, "TestIntersect") assert := internal.NewAssert(t, "TestIntersect")