Skip to content

Commit 116905c

Browse files
committed
added xslices.SortCopy
1 parent 3a11587 commit 116905c

File tree

5 files changed

+19
-8
lines changed

5 files changed

+19
-8
lines changed

internal/xslices/diff.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ func Diff[T any](from, to []T, cmp func(lhs, rhs T) int) (steady, added, dropped
99
added = make([]T, 0, len(to))
1010
dropped = make([]T, 0, len(from))
1111

12-
to = Sort(to, cmp)
13-
from = Sort(from, cmp)
12+
to = SortCopy(to, cmp)
13+
from = SortCopy(from, cmp)
1414

1515
for i, j := 0, 0; ; {
1616
switch {

internal/xslices/sort.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,14 @@ import (
77
"slices"
88
)
99

10-
func Sort[T any](in []T, cmp func(lhs, rhs T) int) (out []T) {
10+
func SortCopy[T any](in []T, cmp func(lhs, rhs T) int) (out []T) {
1111
out = Clone(in)
1212

13-
slices.SortFunc(out, cmp)
13+
Sort(out, cmp)
1414

1515
return out
1616
}
17+
18+
func Sort[T any](in []T, cmp func(lhs, rhs T) int) {
19+
slices.SortFunc(in, cmp)
20+
}

internal/xslices/sort_go1.20.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,18 @@ import (
77
"sort"
88
)
99

10-
func Sort[T any](in []T, cmp func(lhs, rhs T) int) (out []T) {
10+
func SortCopy[T any](in []T, cmp func(lhs, rhs T) int) (out []T) {
1111
out = Clone(in)
1212

13-
sort.Slice(out, func(i, j int) bool {
13+
Sort(out, func(i, j int) bool {
1414
return cmp(out[i], out[j]) < 0
1515
})
1616

1717
return out
1818
}
19+
20+
func Sort[T any](in []T, cmp func(lhs, rhs T) int) {
21+
sort.Slice(in, func(i, j int) bool {
22+
return cmp(in[i], in[j]) < 0
23+
})
24+
}

internal/xslices/sort_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ import (
66
"github.com/stretchr/testify/require"
77
)
88

9-
func TestSort(t *testing.T) {
9+
func TestSortCopy(t *testing.T) {
1010
src := []int{3, 2, 1}
11-
dst := Sort(src, func(lhs, rhs int) int {
11+
dst := SortCopy(src, func(lhs, rhs int) int {
1212
return lhs - rhs
1313
})
1414
require.Equal(t, len(src), len(dst))

internal/xslices/transform.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package xslices
22

33
func Transform[T1, T2 any](in []T1, f func(t T1) T2) (out []T2) {
44
out = make([]T2, len(in))
5+
56
for i, t := range in {
67
out[i] = f(t)
78
}

0 commit comments

Comments
 (0)