Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use map indexing to speed up PickByKeys and OmitByKeys #447

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 6 additions & 5 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ func PickBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool
// Play: https://go.dev/play/p/R1imbuci9qU
func PickByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V {
r := map[K]V{}
for k, v := range in {
if Contains(keys, k) {
for _, k := range keys {
if v, ok := in[k]; ok {
r[k] = v
}
}
Expand Down Expand Up @@ -86,9 +86,10 @@ func OmitBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool
func OmitByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V {
r := map[K]V{}
for k, v := range in {
if !Contains(keys, k) {
r[k] = v
}
r[k] = v
}
for _, k := range keys {
delete(r, k)
}
return r
}
Expand Down
4 changes: 2 additions & 2 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func TestPickByKeys(t *testing.T) {
t.Parallel()
is := assert.New(t)

r1 := PickByKeys(map[string]int{"foo": 1, "bar": 2, "baz": 3}, []string{"foo", "baz"})
r1 := PickByKeys(map[string]int{"foo": 1, "bar": 2, "baz": 3}, []string{"foo", "baz", "qux"})

is.Equal(r1, map[string]int{"foo": 1, "baz": 3})
}
Expand Down Expand Up @@ -84,7 +84,7 @@ func TestOmitByKeys(t *testing.T) {
t.Parallel()
is := assert.New(t)

r1 := OmitByKeys(map[string]int{"foo": 1, "bar": 2, "baz": 3}, []string{"foo", "baz"})
r1 := OmitByKeys(map[string]int{"foo": 1, "bar": 2, "baz": 3}, []string{"foo", "baz", "qux"})

is.Equal(r1, map[string]int{"bar": 2})
}
Expand Down