Skip to content

Commit 9f99f74

Browse files
authored
Use map indexing to speed up PickByKeys and OmitByKeys (#447)
1 parent 71d8341 commit 9f99f74

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

map.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ func PickBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool
4949
// Play: https://go.dev/play/p/R1imbuci9qU
5050
func PickByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V {
5151
r := map[K]V{}
52-
for k, v := range in {
53-
if Contains(keys, k) {
52+
for _, k := range keys {
53+
if v, ok := in[k]; ok {
5454
r[k] = v
5555
}
5656
}
@@ -86,9 +86,10 @@ func OmitBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool
8686
func OmitByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V {
8787
r := map[K]V{}
8888
for k, v := range in {
89-
if !Contains(keys, k) {
90-
r[k] = v
91-
}
89+
r[k] = v
90+
}
91+
for _, k := range keys {
92+
delete(r, k)
9293
}
9394
return r
9495
}

map_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ func TestPickByKeys(t *testing.T) {
5555
t.Parallel()
5656
is := assert.New(t)
5757

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

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

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

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

0 commit comments

Comments
 (0)