github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/enumgen/option.go (about)

     1  package enumgen
     2  
     3  import (
     4  	"sort"
     5  	"strconv"
     6  )
     7  
     8  type Option struct {
     9  	Label string   `json:"label"`
    10  	Str   *string  `json:"str,omitempty"`
    11  	Int   *int64   `json:"int,omitempty"`
    12  	Float *float64 `json:"float,omitempty"`
    13  }
    14  
    15  func (o Option) Value() interface{} {
    16  	if o.Str != nil {
    17  		return *o.Str
    18  	}
    19  	if o.Int != nil {
    20  		return *o.Int
    21  	}
    22  	if o.Float != nil {
    23  		return *o.Float
    24  	}
    25  	return nil
    26  }
    27  
    28  type Options []Option
    29  
    30  var _ sort.Interface = Options{}
    31  
    32  func (o Options) Len() int { return len(o) }
    33  
    34  func (o Options) Values() []interface{} {
    35  	values := make([]interface{}, len(o))
    36  	for i, v := range o {
    37  		values[i] = v.Value()
    38  	}
    39  	return values
    40  }
    41  
    42  func (o Options) Less(i, j int) bool {
    43  	if o[i].Float != nil {
    44  		return *o[i].Float < *o[j].Float
    45  	}
    46  	if o[i].Int != nil {
    47  		return *o[i].Int < *o[j].Int
    48  	}
    49  	return *o[i].Str < *o[j].Str
    50  }
    51  
    52  func (o Options) Swap(i, j int) {
    53  	o[i], o[j] = o[j], o[i]
    54  }
    55  
    56  // NewOption int-string option
    57  func NewOption(i int64, str, label string) *Option {
    58  	ret := &Option{
    59  		Label: label,
    60  		Str:   &str,
    61  		Int:   &i,
    62  	}
    63  	if label == "" {
    64  		ret.Label = str
    65  	}
    66  	return ret
    67  }
    68  
    69  func NewIntOption(i int64, label string) *Option {
    70  	ret := &Option{
    71  		Label: label,
    72  		Int:   &i,
    73  	}
    74  	if label == "" {
    75  		ret.Label = strconv.FormatInt(i, 10)
    76  	}
    77  	return ret
    78  }
    79  
    80  func NewFloatOption(f float64, label string) *Option {
    81  	ret := &Option{
    82  		Label: label,
    83  		Float: &f,
    84  	}
    85  	if label == "" {
    86  		ret.Label = strconv.FormatFloat(f, 'f', -1, 64)
    87  	}
    88  	return ret
    89  }
    90  
    91  func NewStringOption(str, label string) *Option {
    92  	ret := &Option{
    93  		Label: label,
    94  		Str:   &str,
    95  	}
    96  	if label == "" {
    97  		ret.Label = str
    98  	}
    99  	return ret
   100  }