From 260fb795d326e6b8b33a2aa7e26dc72e53a0219b Mon Sep 17 00:00:00 2001 From: dudaodong Date: Sat, 5 Nov 2022 16:52:31 +0800 Subject: [PATCH] feat: add KeyBy for slice --- slice/slice.go | 12 ++++++++++++ slice/slice_test.go | 10 ++++++++++ 2 files changed, 22 insertions(+) diff --git a/slice/slice.go b/slice/slice.go index 097925b..a9e8845 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -833,3 +833,15 @@ func AppendIfAbsent[T comparable](slice []T, value T) []T { } return slice } + +// KeyBy converts a slice to a map based on a callback function +func KeyBy[T any, U comparable](slice []T, iteratee func(T) U) map[U]T { + result := make(map[U]T, len(slice)) + + for _, v := range slice { + k := iteratee(v) + result[k] = v + } + + return result +} diff --git a/slice/slice_test.go b/slice/slice_test.go index f7c4a08..fc3ad5d 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -644,3 +644,13 @@ func TestReplaceAll(t *testing.T) { assert.Equal([]string{"x", "b", "x", "c", "d", "x"}, ReplaceAll(strs, "a", "x")) assert.Equal([]string{"a", "b", "a", "c", "d", "a"}, ReplaceAll(strs, "e", "x")) } + +func TestKeyBy(t *testing.T) { + assert := internal.NewAssert(t, "TestKeyBy") + + result := KeyBy([]string{"a", "ab", "abc"}, func(str string) int { + return len(str) + }) + + assert.Equal(result, map[int]string{1: "a", 2: "ab", 3: "abc"}) +}