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

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