1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 21:02:27 +08:00

feat: add ToMapToSlice function

This commit is contained in:
dudaodong
2022-07-11 11:28:46 +08:00
parent ded42f8ff5
commit 12e979cf3c
2 changed files with 27 additions and 3 deletions

View File

@@ -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, "#")

View File

@@ -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)