From e71cecefea2e51896cb6b71f2912947ac6712230 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Fri, 17 Feb 2023 11:40:20 +0800 Subject: [PATCH] feat: add KeysBy function --- maputil/map.go | 12 ++++++++++++ maputil/map_test.go | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/maputil/map.go b/maputil/map.go index c4a9e92..f9999d3 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -34,6 +34,18 @@ func Values[K comparable, V any](m map[K]V) []V { return values } +// KeysBy creates a slice whose element is the result of function mapper invoked by every map's key. +// todo: +func KeysBy[K comparable, V any, T any](m map[K]V, mapper func(item K) T) []T { + keys := make([]T, 0, len(m)) + + for k := range m { + keys = append(keys, mapper(k)) + } + + return keys +} + // Merge maps, next key will overwrite previous key. // Play: https://go.dev/play/p/H95LENF1uB- func Merge[K comparable, V any](maps ...map[K]V) map[K]V { diff --git a/maputil/map_test.go b/maputil/map_test.go index 53ad992..21d298e 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -41,6 +41,24 @@ func TestValues(t *testing.T) { assert.Equal([]string{"a", "a", "b", "c", "d"}, values) } +func TestKeysBy(t *testing.T) { + assert := internal.NewAssert(t, "TestKeysBy") + + m := map[int]string{ + 1: "a", + 2: "a", + 3: "b", + } + + keys := KeysBy(m, func(n int) int { + return n + 1 + }) + + sort.Ints(keys) + + assert.Equal([]int{2, 3, 4}, keys) +} + func TestMerge(t *testing.T) { assert := internal.NewAssert(t, "TestMerge")