-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathorderby.go
64 lines (57 loc) · 2.08 KB
/
orderby.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package go2linq
import (
"cmp"
"iter"
"slices"
"sort"
"github.com/solsw/errorhelper"
)
func orderByLsPrim[Source any](source iter.Seq[Source], less func(Source, Source) bool) iter.Seq[Source] {
ss := slices.Collect(source)
sort.SliceStable(ss, func(i, j int) bool {
return less(ss[i], ss[j])
})
return slices.Values(ss)
}
// [OrderBy] sorts the elements of a sequence in ascending order.
//
// [OrderBy]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.orderby
func OrderBy[Source cmp.Ordered](source iter.Seq[Source]) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
return orderByLsPrim(source, cmp.Less), nil
}
// [OrderByLs] sorts the elements of a sequence in ascending order using a specified 'less' function.
//
// [OrderByLs]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.orderby
func OrderByLs[Source any](source iter.Seq[Source], less func(Source, Source) bool) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if less == nil {
return nil, errorhelper.CallerError(ErrNilLess)
}
return orderByLsPrim(source, less), nil
}
// [OrderByDesc] sorts the elements of a sequence in descending order.
//
// [OrderByDesc]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.orderbydescending
func OrderByDesc[Source cmp.Ordered](source iter.Seq[Source]) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
return orderByLsPrim(source, ReverseLess(cmp.Less[Source])), nil
}
// [OrderByDescLs] sorts the elements of a sequence in descending order using a specified 'less' function.
//
// [OrderByDescLs]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.orderbydescending
func OrderByDescLs[Source any](source iter.Seq[Source], less func(Source, Source) bool) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if less == nil {
return nil, errorhelper.CallerError(ErrNilLess)
}
return orderByLsPrim(source, ReverseLess(less)), nil
}