fusenapi/utils/collect/collect.go

83 lines
1.6 KiB
Go
Raw Normal View History

2023-06-26 10:19:51 +00:00
package collect
import (
"reflect"
"strconv"
)
func ArrayColumn[R any, T any](arr []T, column string) []R {
var result []R
s := reflect.ValueOf(arr)
for i := 0; i < s.Len(); i++ {
e := s.Index(i)
k := e.FieldByName(column)
result = append(result, k.Interface().(R))
}
return result
}
func ArrayIndex[T any](arr []T, index int) (result T, ok bool) {
if index < len(arr) {
result = arr[index]
ok = true
return
}
ok = false
return
}
func ArrayString2Int(arr interface{}) (result []int64) {
for _, a := range arr.([]string) {
v, err := strconv.ParseInt(a, 10, 64)
if err != nil {
panic(err)
}
result = append(result, v)
}
return result
}
func Array2MapByKey[KEY comparable, VALUE any](arrSrc []VALUE, fieldName string) (result map[KEY]VALUE) {
result = make(map[KEY]VALUE)
arr := reflect.ValueOf(arrSrc)
for i := 0; i < arr.Len(); i++ {
srcv := arr.Index(i)
fv := srcv.Elem().FieldByName(fieldName)
k := fv.Interface().(KEY)
result[k] = srcv.Interface().(VALUE)
}
return result
}
func Array2MapByKeyTag[KEY comparable, VALUE any](arrSrc []VALUE, tag string) (result map[KEY]VALUE) {
arr := reflect.ValueOf(arrSrc)
if arr.Len() == 0 {
return result
}
result = make(map[KEY]VALUE)
eleType := arr.Index(0).Elem().Type()
for j := 0; j < eleType.NumField(); j++ {
if value, ok := eleType.Field(j).Tag.Lookup("json"); ok && value == tag {
for i := 0; i < arr.Len(); i++ {
srcv := arr.Index(i)
fv := srcv.Elem().Field(j)
k := fv.Interface().(KEY)
result[k] = srcv.Interface().(VALUE)
}
return
}
}
return result
}