Skip to content

Commit

Permalink
compare: add Bool comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
creachadair committed Oct 23, 2024
1 parent fea925b commit 988ca23
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions compare/compare.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,13 @@ func Time(a, b time.Time) int { return a.Compare(b) }
func Reversed[T any](c func(a, b T) int) func(a, b T) int {
return func(a, b T) int { return -c(a, b) }
}

// Bool is a comparison function for bool values that orders false before true.
func Bool(a, b bool) int {
if a == b {
return 0
} else if a {
return 1
}
return -1
}
17 changes: 17 additions & 0 deletions compare/compare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,20 @@ func TestReversed(t *testing.T) {
t.Errorf("Reversed output is not sorted: %v", buf)
}
}

func TestBool(t *testing.T) {
tests := []struct {
a, b bool
want int
}{
{false, false, 0},
{false, true, -1},
{true, false, 1},
{true, true, 0},
}
for _, tc := range tests {
if got := compare.Bool(tc.a, tc.b); got != tc.want {
t.Errorf("Bool(%v, %v): got %v, want %v", tc.a, tc.b, got, tc.want)
}
}
}

0 comments on commit 988ca23

Please sign in to comment.