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

maps add Kvs function #71

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.
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