From d59063075477452136d817c36b8cc958acb8c5df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E8=B6=85=E4=BA=BA?= <67250607+fcorpo@users.noreply.github.com> Date: Sun, 21 Jan 2024 19:18:43 +0800 Subject: [PATCH] maps: add Kvs, and values is keys order --- maps/maps.go | 12 ++++++++++++ maps/maps_test.go | 11 +++++++++++ 2 files changed, 23 insertions(+) diff --git a/maps/maps.go b/maps/maps.go index ecc0dabb7..a7a119660 100644 --- a/maps/maps.go +++ b/maps/maps.go @@ -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 { diff --git a/maps/maps_test.go b/maps/maps_test.go index bf7c6f4bb..ef5d67045 100644 --- a/maps/maps_test.go +++ b/maps/maps_test.go @@ -10,6 +10,8 @@ import ( "strconv" "testing" + "github.com/google/go-cmp/cmp" + "golang.org/x/exp/slices" ) @@ -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)