gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/def/default.go (about)

     1  package def
     2  
     3  func Condition[X any](condition bool, yes X, no X) X {
     4  	if condition {
     5  		return yes
     6  	} else {
     7  		return no
     8  	}
     9  }
    10  
    11  func ConditionFunc[X any](condition bool, yes func() X, no func() X) X {
    12  	if condition {
    13  		return yes()
    14  	} else {
    15  		return no()
    16  	}
    17  }
    18  
    19  func SetDefault[X comparable](v X, def X) X {
    20  	var zero X
    21  	if v == zero {
    22  		return def
    23  	}
    24  	return v
    25  }
    26  
    27  func SetDefaultIf[X any](v X, def X, condition func(v X) bool) X {
    28  	if condition(v) {
    29  		return def
    30  	}
    31  	return v
    32  }
    33  
    34  func SetDefaultEqual[X comparable](v X, def X, ref X) X {
    35  	if v == ref {
    36  		return def
    37  	}
    38  	return v
    39  }
    40  
    41  func SetterDefault[X comparable](v X, setter func() X) X {
    42  	var zero X
    43  	if v == zero {
    44  		return setter()
    45  	}
    46  	return v
    47  }
    48  
    49  func SetterDefaultIf[X any](v X, setter func() X, condition func(v X) bool) X {
    50  	if condition(v) {
    51  		return setter()
    52  	}
    53  	return v
    54  }
    55  
    56  func SetterDefaultEqual[X comparable](v X, setter func() X, ref X) X {
    57  	if v == ref {
    58  		return setter()
    59  	}
    60  	return v
    61  }
    62  
    63  func SetDefaultP[X comparable](vp *X, def X) {
    64  	var zero X
    65  	if *vp == zero {
    66  		*vp = def
    67  	}
    68  }
    69  
    70  func SetDefaultPIf[X any](vp *X, def X, condition func(v X) bool) {
    71  	if condition(*vp) {
    72  		*vp = def
    73  	}
    74  }
    75  
    76  func SetDefaultPEqual[X comparable](vp *X, def X, ref X) {
    77  	if *vp == ref {
    78  		*vp = def
    79  	}
    80  }
    81  
    82  func SetterDefaultP[X comparable](vp *X, setter func() X) {
    83  	var zero X
    84  	if *vp == zero {
    85  		*vp = setter()
    86  	}
    87  }
    88  
    89  func SetterDefaultPIf[X any](vp *X, setter func() X, condition func(v X) bool) {
    90  	if condition(*vp) {
    91  		*vp = setter()
    92  	}
    93  }
    94  
    95  func SetterDefaultPIfEqual[X comparable](vp *X, setter func() X, ref X) {
    96  	if *vp == ref {
    97  		*vp = setter()
    98  	}
    99  }