mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add FilterByKeys function
This commit is contained in:
@@ -4,7 +4,11 @@
|
||||
// Package maputil includes some functions to manipulate map.
|
||||
package maputil
|
||||
|
||||
import "reflect"
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/duke-git/lancet/v2/slice"
|
||||
)
|
||||
|
||||
// Keys returns a slice of the map's keys.
|
||||
// Play: https://go.dev/play/p/xNB5bTb97Wd
|
||||
@@ -93,6 +97,19 @@ func Filter[K comparable, V any](m map[K]V, predicate func(key K, value V) bool)
|
||||
return result
|
||||
}
|
||||
|
||||
// FilterByKeys iterates over map, return a new map whose keys are all given keys.
|
||||
// todo:
|
||||
func FilterByKeys[K comparable, V any](m map[K]V, keys []K) map[K]V {
|
||||
result := make(map[K]V)
|
||||
|
||||
for k, v := range m {
|
||||
if slice.Contain(keys, k) {
|
||||
result[k] = v
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Intersect iterates over maps, return a new map of key and value pairs in all given maps.
|
||||
// Play: https://go.dev/play/p/Zld0oj3sjcC
|
||||
func Intersect[K comparable, V any](maps ...map[K]V) map[K]V {
|
||||
|
||||
@@ -149,6 +149,25 @@ func TestFilter(t *testing.T) {
|
||||
}, acturl)
|
||||
}
|
||||
|
||||
func TestFilterByKeys(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestFilterByKeys")
|
||||
|
||||
m := map[string]int{
|
||||
"a": 1,
|
||||
"b": 2,
|
||||
"c": 3,
|
||||
"d": 4,
|
||||
"e": 5,
|
||||
}
|
||||
|
||||
acturl := FilterByKeys(m, []string{"a", "b"})
|
||||
|
||||
assert.Equal(map[string]int{
|
||||
"a": 1,
|
||||
"b": 2,
|
||||
}, acturl)
|
||||
}
|
||||
|
||||
func TestIntersect(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestIntersect")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user