Skip to content

Commit acf26bb

Browse files
authored
Adding support for Slice sorting (Asc & Desc) (#37)
* creating slice and pointer changes * removing extra file * switching to use 'sliceStable'
1 parent 539f8c5 commit acf26bb

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

slices.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package underscore
2+
3+
import (
4+
"sort"
5+
6+
"golang.org/x/exp/constraints"
7+
)
8+
9+
// sort any slice ASENDING
10+
func SortSliceASC[T constraints.Ordered](s []T) {
11+
sort.SliceStable(s, func(i, j int) bool {
12+
return s[i] < s[j]
13+
})
14+
}
15+
16+
// sort any slice DESCENDING
17+
func SortSliceDESC[T constraints.Ordered](s []T) {
18+
sort.SliceStable(s, func(i, j int) bool {
19+
return s[i] > s[j]
20+
})
21+
}

slices_test.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package underscore_test
2+
3+
import (
4+
"testing"
5+
6+
u "github.com/rjNemo/underscore"
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func TestSortSliceAscString(t *testing.T) {
11+
slc := []string{"c", "a", "b"}
12+
expected := []string{"a", "b", "c"}
13+
u.SortSliceASC(slc)
14+
15+
assert.Equal(t, expected, slc)
16+
}
17+
18+
func TestSortSliceDescString(t *testing.T) {
19+
slc := []string{"c", "a", "b"}
20+
expected := []string{"c", "b", "a"}
21+
u.SortSliceDESC(slc)
22+
23+
assert.Equal(t, expected, slc)
24+
}
25+
26+
func TestSortSliceAscInt(t *testing.T) {
27+
slc := []int{1, 4, 3, 5, 2}
28+
expected := []int{1, 2, 3, 4, 5}
29+
u.SortSliceASC(slc)
30+
31+
assert.Equal(t, expected, slc)
32+
}
33+
34+
func TestSortSliceDescInt(t *testing.T) {
35+
slc := []int{1, 4, 3, 5, 2}
36+
expected := []int{5, 4, 3, 2, 1}
37+
u.SortSliceDESC(slc)
38+
39+
assert.Equal(t, expected, slc)
40+
}
41+
42+
func TestSortSliceAscFloat64(t *testing.T) {
43+
slc := []float64{1.0, 1.2, 1.1, 1.5, 1.01}
44+
expected := []float64{1, 1.01, 1.1, 1.2, 1.5}
45+
u.SortSliceASC(slc)
46+
47+
assert.Equal(t, expected, slc)
48+
}
49+
50+
func TestSortSliceDescFloat64(t *testing.T) {
51+
slc := []float64{1.0, 1.2, 1.1, 1.5, 1.01}
52+
expected := []float64{1.5, 1.2, 1.1, 1.01, 1}
53+
u.SortSliceDESC(slc)
54+
55+
assert.Equal(t, expected, slc)
56+
}

0 commit comments

Comments
 (0)