go-ml.dev/pkg/base@v0.0.0-20200610162856-60c38abac71b/fu/option.go (about)

     1  package fu
     2  
     3  import (
     4  	"reflect"
     5  )
     6  
     7  func Option(t interface{}, o interface{}) reflect.Value {
     8  	xs := reflect.ValueOf(o)
     9  	tv := reflect.ValueOf(t)
    10  	for i := 0; i < xs.Len(); i++ {
    11  		x := xs.Index(i)
    12  		if x.Kind() == reflect.Interface {
    13  			x = x.Elem()
    14  		}
    15  		if x.Type() == tv.Type() {
    16  			return x
    17  		}
    18  	}
    19  	return tv
    20  }
    21  
    22  func IfsOption(t interface{}, o []interface{}) interface{} {
    23  	return Option(t, o).Interface()
    24  }
    25  
    26  func StrOption(t interface{}, o []interface{}) string {
    27  	return Option(t, o).String()
    28  }
    29  
    30  func IntOption(t interface{}, o []interface{}) int {
    31  	return int(Option(t, o).Int())
    32  }
    33  
    34  func FloatOption(t interface{}, o []interface{}) float64 {
    35  	return Option(t, o).Float()
    36  }
    37  
    38  func BoolOption(t interface{}, o []interface{}) bool {
    39  	return Option(t, o).Bool()
    40  }
    41  
    42  func RuneOption(t interface{}, o []interface{}) rune {
    43  	return rune(Option(t, o).Int())
    44  }
    45  
    46  func MultiOption(o []interface{}, t ...interface{}) (reflect.Value, int) {
    47  	for _, x := range o {
    48  		for i, tv := range t {
    49  			v := reflect.ValueOf(x)
    50  			if v.Type() == reflect.TypeOf(tv) {
    51  				return v, i
    52  			}
    53  		}
    54  	}
    55  	return reflect.ValueOf(t[0]), 0
    56  }
    57  
    58  func StrMultiOption(o []interface{}, t ...interface{}) (string, int) {
    59  	v, i := MultiOption(o, t...)
    60  	return v.String(), i
    61  }
    62  
    63  func AllStrOptions(o []interface{}, t ...interface{}) []string {
    64  	r := []string{}
    65  	for _, x := range o {
    66  		for _, tv := range t {
    67  			v := reflect.ValueOf(x)
    68  			if v.Type() == reflect.TypeOf(tv) {
    69  				r = append(r, v.String())
    70  			}
    71  		}
    72  	}
    73  	return r
    74  }