mirror of
https://github.com/rjNemo/underscore
synced 2026-06-10 20:46:42 +00:00
Added in an OrderBy function
This commit is contained in:
parent
3066810f92
commit
a197836c1d
2 changed files with 53 additions and 0 deletions
22
orderBy.go
Normal file
22
orderBy.go
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
package underscore
|
||||||
|
|
||||||
|
func OrderBy[T any](list []T, predicate func(T, T) bool) []T {
|
||||||
|
swaps := true
|
||||||
|
var tmp T
|
||||||
|
|
||||||
|
for swaps {
|
||||||
|
swaps = false
|
||||||
|
|
||||||
|
for i := 0; i < len(list)-1; i++ {
|
||||||
|
if predicate(list[i], list[i+1]) {
|
||||||
|
swaps = true
|
||||||
|
tmp = list[i]
|
||||||
|
|
||||||
|
list[i] = list[i+1]
|
||||||
|
list[i+1] = tmp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return list
|
||||||
|
}
|
||||||
31
orderBy_test.go
Normal file
31
orderBy_test.go
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
package underscore_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
u "github.com/rjNemo/underscore"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_OrderBy_Asc(t *testing.T) {
|
||||||
|
set := u.Range(5, 0)
|
||||||
|
want := u.Range(0, 5)
|
||||||
|
|
||||||
|
result := u.OrderBy(set, func(left int, right int) bool {
|
||||||
|
return left > right
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Equal(t, want, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_OrderBy_Desc(t *testing.T) {
|
||||||
|
set := u.Range(0, 5)
|
||||||
|
want := u.Range(5, 0)
|
||||||
|
|
||||||
|
result := u.OrderBy(set, func(left int, right int) bool {
|
||||||
|
return left < right
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Equal(t, want, result)
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue