diff --git a/convertor/convertor.go b/convertor/convertor.go index dea10f5..559833b 100644 --- a/convertor/convertor.go +++ b/convertor/convertor.go @@ -189,7 +189,7 @@ func ToPointer[T any](value T) *T { return &value } -// ToMap convert a slice or an array of structs to a map +// ToMap convert a slice or an array of structs to a map based on iteratee function func ToMap[T any, K comparable, V any](array []T, iteratee func(T) (K, V)) map[K]V { res := make(map[K]V, len(array)) for _, item := range array { @@ -230,6 +230,17 @@ func StructToMap(value any) (map[string]any, error) { return res, nil } +// MapToSlice convert a map to a slice based on iteratee function +func MapToSlice[T any, K comparable, V any](aMap map[K]V, iteratee func(K, V) T) []T { + res := make([]T, 0, len(aMap)) + + for k, v := range aMap { + res = append(res, iteratee(k, v)) + } + + return res +} + // ColorHexToRGB convert hex color to rgb color func ColorHexToRGB(colorHex string) (red, green, blue int) { colorHex = strings.TrimPrefix(colorHex, "#") diff --git a/convertor/convertor_test.go b/convertor/convertor_test.go index d05ed98..d6bbdc7 100644 --- a/convertor/convertor_test.go +++ b/convertor/convertor_test.go @@ -2,6 +2,7 @@ package convertor import ( "fmt" + "strconv" "testing" "github.com/duke-git/lancet/v2/internal" @@ -160,7 +161,7 @@ func TestToJson(t *testing.T) { } func TestToMap(t *testing.T) { - assert := internal.NewAssert(t, "TestStructToMap") + assert := internal.NewAssert(t, "TestToMap") type Message struct { name string @@ -190,10 +191,22 @@ func TestStructToMap(t *testing.T) { 100, } pm, _ := StructToMap(p) - var expected = map[string]any{"name": "test"} + + expected := map[string]any{"name": "test"} assert.Equal(expected, pm) } +func TestMapToSlice(t *testing.T) { + assert := internal.NewAssert(t, "TestMapToSlice") + + aMap := map[string]int{"a": 1, "b": 2, "c": 3} + result := MapToSlice(aMap, func(key string, value int) string { + return key + ":" + strconv.Itoa(value) + }) + + assert.Equal([]string{"a:1", "b:2", "c:3"}, result) +} + func TestColorHexToRGB(t *testing.T) { colorHex := "#003366" r, g, b := ColorHexToRGB(colorHex)