Skip to content

Commit

Permalink
maps: add Kvs, and values is keys order
Browse files Browse the repository at this point in the history
  • Loading branch information
xx1906 committed Jan 22, 2024
1 parent 1b97071 commit d590630
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
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

0 comments on commit d590630

Please sign in to comment.