Skip to content

Commit

Permalink
Common: Add common.Sort for stringers
Browse files Browse the repository at this point in the history
  • Loading branch information
gbjk committed Jul 12, 2024
1 parent 83568f0 commit 4f3387c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
10 changes: 10 additions & 0 deletions common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"path/filepath"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -666,3 +667,12 @@ func Batch[S ~[]E, E any](blobs S, batchSize int) (batches []S) {
}
return
}

// Sort takes a slice of fmt.Stringer implementers and returns a new sorted slice
func Sort[S ~[]E, E fmt.Stringer](x S) S {
n := slices.Clone(x)
slices.SortFunc(n, func(a, b E) int {
return strings.Compare(a.String(), b.String())
})
return n
}
11 changes: 11 additions & 0 deletions common/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -866,3 +866,14 @@ func TestBatch(t *testing.T) {
require.Len(t, b[1], 3)
require.Len(t, b[2], 1)
}

type A int

func (a A) String() string {
return strconv.Itoa(int(a))
}

// TestSort exercises Sort
func TestSort(t *testing.T) {
assert.Equal(t, []A{1, 2, 5, 6}, Sort([]A{6, 2, 5, 1}))
}

0 comments on commit 4f3387c

Please sign in to comment.