Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions maps/maps.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@ func Values[M ~map[K]V, K comparable, V any](m M) []V {
return r
}

// Kvs returns the keys and values of the map m.
// The keys and values will be in an indeterminate order.
func Kvs[M ~map[K]V, K comparable, V any](m M) ([]K, []V) {
rK := make([]K, 0, len(m))
rV := make([]V, 0, len(m))
for k, v := range m {
rK = append(rK, k)
rV = append(rV, v)
}
return rK, rV
}

// Equal reports whether two maps contain the same key/value pairs.
// Values are compared using ==.
func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool {
Expand Down
11 changes: 11 additions & 0 deletions maps/maps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"strconv"
"testing"

"github.com/google/go-cmp/cmp"

"golang.org/x/exp/slices"
)

Expand Down Expand Up @@ -48,6 +50,15 @@ func TestValues(t *testing.T) {
}
}

func TestKvs(t *testing.T) {
ks, vs := Kvs(m1)
for idx, k := range ks {
if !cmp.Equal(m1[k], vs[idx]) {
t.Errorf("key %v want value %v, but %v", k, m1[k], vs[idx])
}
}
}

func TestEqual(t *testing.T) {
if !Equal(m1, m1) {
t.Errorf("Equal(%v, %v) = false, want true", m1, m1)
Expand Down