Skip to content

Commit 7cbd3d1

Browse files
authored
refactor: use slices.SortFunc instead of sort.Slice (#1191)
1 parent cadb2dd commit 7cbd3d1

File tree

2 files changed

+51
-4
lines changed

2 files changed

+51
-4
lines changed

formatter/friendly.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ package formatter
22

33
import (
44
"bytes"
5+
"cmp"
56
"fmt"
67
"io"
7-
"sort"
8+
"slices"
89
"strings"
910

1011
"github.com/fatih/color"
@@ -112,12 +113,12 @@ func (f *Friendly) printStatistics(w io.Writer, header string, stats map[string]
112113
if len(stats) == 0 {
113114
return
114115
}
115-
var data []statEntry
116+
data := make([]statEntry, 0, len(stats))
116117
for name, total := range stats {
117118
data = append(data, statEntry{name, total})
118119
}
119-
sort.Slice(data, func(i, j int) bool {
120-
return data[i].failures > data[j].failures
120+
slices.SortFunc(data, func(a, b statEntry) int {
121+
return -cmp.Compare(a.failures, b.failures)
121122
})
122123
formatted := [][]string{}
123124
for _, entry := range data {

formatter/friendly_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package formatter
2+
3+
import (
4+
"bytes"
5+
"testing"
6+
)
7+
8+
func TestFriendly_printStatistics(t *testing.T) {
9+
tests := []struct {
10+
name string
11+
stats map[string]int
12+
expected string
13+
}{
14+
{
15+
name: "no stats",
16+
stats: map[string]int{},
17+
expected: "",
18+
},
19+
{
20+
name: "nil stats",
21+
stats: nil,
22+
expected: "",
23+
},
24+
{
25+
name: "single stat",
26+
stats: map[string]int{"rule1": 1},
27+
expected: "Warnings:\n 1 rule1 \n\n",
28+
},
29+
{
30+
name: "multiple stats sorted by failures desc",
31+
stats: map[string]int{"rule2": 2, "rule1": 1, "rule3": 3},
32+
expected: "Warnings:\n 3 rule3 \n 2 rule2 \n 1 rule1 \n\n",
33+
},
34+
}
35+
36+
for _, tt := range tests {
37+
t.Run(tt.name, func(t *testing.T) {
38+
f := &Friendly{}
39+
var buf bytes.Buffer
40+
f.printStatistics(&buf, "Warnings:", tt.stats)
41+
if got := buf.String(); got != tt.expected {
42+
t.Errorf("got %q, want %q", got, tt.expected)
43+
}
44+
})
45+
}
46+
}

0 commit comments

Comments
 (0)