types/bools: add IfElse (#14272)

The IfElse function is equivalent to the ternary (c ? a : b) operator
in many other languages like C. Unfortunately, this function
cannot perform short-circuit evaluation like in many other languages,
but this is a restriction that's not much different
than the pre-existing cmp.Or function.

The argument against ternary operators in Go is that
nested ternary operators become unreadable
(e.g., (c1 ? (c2 ? a : b) : (c2 ? x : y))).
But a single layer of ternary expressions can sometimes
make code much more readable.

Having the bools.IfElse function gives code authors the
ability to decide whether use of this is more readable or not.
Obviously, code authors will need to be judicious about
their use of this helper function.
Readability is more of an art than a science.

Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
This commit is contained in:
Joe Tsai 2024-12-11 10:55:33 -08:00 committed by GitHub
parent 0045860060
commit c9188d7760
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 37 additions and 17 deletions

28
types/bools/bools.go Normal file
View File

@ -0,0 +1,28 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// Package bools contains the [Compare] and [Select] functions.
package bools
// Compare compares two boolean values as if false is ordered before true.
func Compare[T ~bool](x, y T) int {
switch {
case x == false && y == true:
return -1
case x == true && y == false:
return +1
default:
return 0
}
}
// IfElse is a ternary operator that returns trueVal if condExpr is true
// otherwise it returns falseVal.
// IfElse(c, a, b) is roughly equivalent to (c ? a : b) in languages like C.
func IfElse[T any](condExpr bool, trueVal T, falseVal T) T {
if condExpr {
return trueVal
} else {
return falseVal
}
}

View File

@ -19,3 +19,12 @@ func TestCompare(t *testing.T) {
t.Errorf("Compare(true, true) = %v, want 0", got)
}
}
func TestIfElse(t *testing.T) {
if got := IfElse(true, 0, 1); got != 0 {
t.Errorf("IfElse(true, 0, 1) = %v, want 0", got)
}
if got := IfElse(false, 0, 1); got != 1 {
t.Errorf("IfElse(false, 0, 1) = %v, want 1", got)
}
}

View File

@ -1,17 +0,0 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// Package bools contains the bools.Compare function.
package bools
// Compare compares two boolean values as if false is ordered before true.
func Compare[T ~bool](x, y T) int {
switch {
case x == false && y == true:
return -1
case x == true && y == false:
return +1
default:
return 0
}
}