Skip to content

Commit d590630

Browse files
committed
maps: add Kvs, and values is keys order
1 parent 1b97071 commit d590630

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

maps/maps.go

+12
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,18 @@ func Values[M ~map[K]V, K comparable, V any](m M) []V {
2525
return r
2626
}
2727

28+
// Kvs returns the keys and values of the map m.
29+
// The keys and values will be in an indeterminate order.
30+
func Kvs[M ~map[K]V, K comparable, V any](m M) ([]K, []V) {
31+
rK := make([]K, 0, len(m))
32+
rV := make([]V, 0, len(m))
33+
for k, v := range m {
34+
rK = append(rK, k)
35+
rV = append(rV, v)
36+
}
37+
return rK, rV
38+
}
39+
2840
// Equal reports whether two maps contain the same key/value pairs.
2941
// Values are compared using ==.
3042
func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool {

maps/maps_test.go

+11
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import (
1010
"strconv"
1111
"testing"
1212

13+
"github.com/google/go-cmp/cmp"
14+
1315
"golang.org/x/exp/slices"
1416
)
1517

@@ -48,6 +50,15 @@ func TestValues(t *testing.T) {
4850
}
4951
}
5052

53+
func TestKvs(t *testing.T) {
54+
ks, vs := Kvs(m1)
55+
for idx, k := range ks {
56+
if !cmp.Equal(m1[k], vs[idx]) {
57+
t.Errorf("key %v want value %v, but %v", k, m1[k], vs[idx])
58+
}
59+
}
60+
}
61+
5162
func TestEqual(t *testing.T) {
5263
if !Equal(m1, m1) {
5364
t.Errorf("Equal(%v, %v) = false, want true", m1, m1)

0 commit comments

Comments
 (0)