diff --git a/anyx/README.md b/anyx/README.md index 52ddf92..1b8fbe4 100644 --- a/anyx/README.md +++ b/anyx/README.md @@ -57,5 +57,8 @@ func ToUint32(i any) (uint32, error) func ToUint64(i any) (uint64, error) // ToBool 将给定的值转换为bool -func ToBool(i any) bool +func ToBool(i any) bool + +// Ternary 三元运算符 +func Ternary[T any](expr bool, a, b T) T ``` \ No newline at end of file diff --git a/anyx/ternary.go b/anyx/ternary.go new file mode 100644 index 0000000..88902f0 --- /dev/null +++ b/anyx/ternary.go @@ -0,0 +1,11 @@ +package anyx + +// Ternary 三元运算符 +// 根据表达式 expr 的布尔值,返回 a 或 b 中的一个 +// 如果 expr 为 true,则返回 a;否则返回 b +func Ternary[T any](expr bool, a, b T) T { + if expr { + return a + } + return b +} diff --git a/anyx/ternary_example_test.go b/anyx/ternary_example_test.go new file mode 100644 index 0000000..977ad18 --- /dev/null +++ b/anyx/ternary_example_test.go @@ -0,0 +1,13 @@ +package anyx + +import "fmt" + +func ExampleTernary() { + age := 15 + res := Ternary(age < 18, "未成年", "成年") + + fmt.Println(res) + + // Output: + // 未成年 +} diff --git a/anyx/ternary_test.go b/anyx/ternary_test.go new file mode 100644 index 0000000..94e8d22 --- /dev/null +++ b/anyx/ternary_test.go @@ -0,0 +1,43 @@ +package anyx + +import ( + "testing" +) + +func TestTernary(t *testing.T) { + tests := []struct { + name string + expr bool + a any + b any + expected any + }{ + {"TrueCase_String", true, "yes", "no", "yes"}, + {"FalseCase_String", false, "yes", "no", "no"}, + {"TrueCase_Int", true, 1, 2, 1}, + {"FalseCase_Int", false, 1, 2, 2}, + {"TrueCase_Struct", true, struct{ X int }{1}, struct{ X int }{2}, struct{ X int }{1}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + switch tt.a.(type) { + case string: + result := Ternary(tt.expr, tt.a.(string), tt.b.(string)) + if result != tt.expected.(string) { + t.Errorf("expected %v, got %v", tt.expected, result) + } + case int: + result := Ternary(tt.expr, tt.a.(int), tt.b.(int)) + if result != tt.expected.(int) { + t.Errorf("expected %v, got %v", tt.expected, result) + } + case struct{ X int }: + result := Ternary(tt.expr, tt.a.(struct{ X int }), tt.b.(struct{ X int })) + if result != tt.expected.(struct{ X int }) { + t.Errorf("expected %+v, got %+v", tt.expected, result) + } + } + }) + } +}