gitlab.com/evatix-go/core@v1.3.55/coredata/coredynamic/SliceItemsSimpleProcessorAsStrings.go (about)

     1  package coredynamic
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"gitlab.com/evatix-go/core/errcore"
     7  )
     8  
     9  func SliceItemsSimpleProcessorAsStrings(
    10  	reflectVal reflect.Value,
    11  	isSkipEmpty bool,
    12  	processor func(index int, item interface{}) (result string),
    13  ) ([]string, error) {
    14  	if reflectVal.Kind() == reflect.Ptr {
    15  		return SliceItemsAsStrings(
    16  			reflect.Indirect(reflect.ValueOf(reflectVal)))
    17  	}
    18  
    19  	k := reflectVal.Kind()
    20  	isSliceOrArray := k == reflect.Slice ||
    21  		k == reflect.Array
    22  
    23  	if !isSliceOrArray {
    24  		return []string{},
    25  			errcore.TypeMismatchType.Error(
    26  				"Reflection is not Slice or Array", reflectVal)
    27  	}
    28  
    29  	length := reflectVal.Len()
    30  	slice := make([]string, 0, length)
    31  
    32  	for i := 0; i < length; i++ {
    33  		value := reflectVal.Index(i)
    34  		result := processor(
    35  			i, value)
    36  
    37  		if isSkipEmpty && result == "" {
    38  			continue
    39  		}
    40  
    41  		slice = append(
    42  			slice,
    43  			result)
    44  	}
    45  
    46  	return slice, nil
    47  }