Adding support for Slice sorting (Asc & Desc) (#37)

* creating slice and pointer changes

* removing extra file

* switching to use 'sliceStable'
This commit is contained in:
Carlos A Saavedra 2024-11-01 04:18:33 -05:00 committed by GitHub
parent 539f8c518a
commit acf26bbaf9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 77 additions and 0 deletions

21
slices.go Normal file
View file

@ -0,0 +1,21 @@
package underscore
import (
"sort"
"golang.org/x/exp/constraints"
)
// sort any slice ASENDING
func SortSliceASC[T constraints.Ordered](s []T) {
sort.SliceStable(s, func(i, j int) bool {
return s[i] < s[j]
})
}
// sort any slice DESCENDING
func SortSliceDESC[T constraints.Ordered](s []T) {
sort.SliceStable(s, func(i, j int) bool {
return s[i] > s[j]
})
}

56
slices_test.go Normal file
View file

@ -0,0 +1,56 @@
package underscore_test
import (
"testing"
u "github.com/rjNemo/underscore"
"github.com/stretchr/testify/assert"
)
func TestSortSliceAscString(t *testing.T) {
slc := []string{"c", "a", "b"}
expected := []string{"a", "b", "c"}
u.SortSliceASC(slc)
assert.Equal(t, expected, slc)
}
func TestSortSliceDescString(t *testing.T) {
slc := []string{"c", "a", "b"}
expected := []string{"c", "b", "a"}
u.SortSliceDESC(slc)
assert.Equal(t, expected, slc)
}
func TestSortSliceAscInt(t *testing.T) {
slc := []int{1, 4, 3, 5, 2}
expected := []int{1, 2, 3, 4, 5}
u.SortSliceASC(slc)
assert.Equal(t, expected, slc)
}
func TestSortSliceDescInt(t *testing.T) {
slc := []int{1, 4, 3, 5, 2}
expected := []int{5, 4, 3, 2, 1}
u.SortSliceDESC(slc)
assert.Equal(t, expected, slc)
}
func TestSortSliceAscFloat64(t *testing.T) {
slc := []float64{1.0, 1.2, 1.1, 1.5, 1.01}
expected := []float64{1, 1.01, 1.1, 1.2, 1.5}
u.SortSliceASC(slc)
assert.Equal(t, expected, slc)
}
func TestSortSliceDescFloat64(t *testing.T) {
slc := []float64{1.0, 1.2, 1.1, 1.5, 1.01}
expected := []float64{1.5, 1.2, 1.1, 1.01, 1}
u.SortSliceDESC(slc)
assert.Equal(t, expected, slc)
}