From ac4ea73cdbf6a25c169dbdce5e46defd56553600 Mon Sep 17 00:00:00 2001 From: GrĂ©goire DuchĂȘne Date: Sun, 11 Dec 2022 14:15:03 +0000 Subject: Add MapKeys --- util.go | 14 ++++++++++++++ util_test.go | 11 +++++++++++ 2 files changed, 25 insertions(+) diff --git a/util.go b/util.go index ec2a3dd..47a785a 100644 --- a/util.go +++ b/util.go @@ -3,6 +3,20 @@ package core +// MapKeys returns a slice containing all the keys of the map supplied. +// It basically is https://pkg.go.dev/golang.org/x/exp/maps#Keys, but +// that package is still unstable. +func MapKeys[T ~map[K]V, K comparable, V any](m T) []K { + if len(m) == 0 { + return nil + } + ret := make([]K, 0, len(m)) + for k := range m { + ret = append(ret, k) + } + return ret +} + // Must panics if err is not nil. It returns val otherwise. func Must[T any](val T, err error) T { if err != nil { diff --git a/util_test.go b/util_test.go index a9b297e..f8731e5 100644 --- a/util_test.go +++ b/util_test.go @@ -5,6 +5,7 @@ package core_test import ( "errors" + "sort" "testing" "github.com/google/go-cmp/cmp" @@ -13,6 +14,16 @@ import ( "go.awhk.org/core" ) +func TestMapKeys(s *testing.T) { + t := core.T{T: s} + + t.AssertEqual(([]string)(nil), core.MapKeys[map[string]int](nil)) + t.AssertEqual(([]string)(nil), core.MapKeys(map[string]int{})) + keys := core.MapKeys(map[string]int{"foo": 1, "bar": 2}) + sort.Strings(keys) + t.AssertEqual([]string{"bar", "foo"}, keys) +} + func TestMust(s *testing.T) { t := core.T{T: s, Options: []cmp.Option{cmpopts.EquateErrors()}} -- cgit v1.2.3-70-g09d2