Skip to content

Commit

Permalink
refactor: use slices.SortFunc instead of sort.Slice (#1191)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandear authored Dec 13, 2024
1 parent cadb2dd commit 7cbd3d1
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
9 changes: 5 additions & 4 deletions formatter/friendly.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package formatter

import (
"bytes"
"cmp"
"fmt"
"io"
"sort"
"slices"
"strings"

"github.com/fatih/color"
Expand Down Expand Up @@ -112,12 +113,12 @@ func (f *Friendly) printStatistics(w io.Writer, header string, stats map[string]
if len(stats) == 0 {
return
}
var data []statEntry
data := make([]statEntry, 0, len(stats))
for name, total := range stats {
data = append(data, statEntry{name, total})
}
sort.Slice(data, func(i, j int) bool {
return data[i].failures > data[j].failures
slices.SortFunc(data, func(a, b statEntry) int {
return -cmp.Compare(a.failures, b.failures)
})
formatted := [][]string{}
for _, entry := range data {
Expand Down
46 changes: 46 additions & 0 deletions formatter/friendly_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package formatter

import (
"bytes"
"testing"
)

func TestFriendly_printStatistics(t *testing.T) {
tests := []struct {
name string
stats map[string]int
expected string
}{
{
name: "no stats",
stats: map[string]int{},
expected: "",
},
{
name: "nil stats",
stats: nil,
expected: "",
},
{
name: "single stat",
stats: map[string]int{"rule1": 1},
expected: "Warnings:\n 1 rule1 \n\n",
},
{
name: "multiple stats sorted by failures desc",
stats: map[string]int{"rule2": 2, "rule1": 1, "rule3": 3},
expected: "Warnings:\n 3 rule3 \n 2 rule2 \n 1 rule1 \n\n",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := &Friendly{}
var buf bytes.Buffer
f.printStatistics(&buf, "Warnings:", tt.stats)
if got := buf.String(); got != tt.expected {
t.Errorf("got %q, want %q", got, tt.expected)
}
})
}
}

0 comments on commit 7cbd3d1

Please # to comment.