-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort_reverse.go
More file actions
36 lines (33 loc) · 1.02 KB
/
sort_reverse.go
File metadata and controls
36 lines (33 loc) · 1.02 KB
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
package enumerators
import (
"sort"
)
// Sort sorts the elements of the enumerator using the provided less function.
// The enumerator is consumed and sorted eagerly, then returned as a new enumerator.
// The less function should return true if a < b.
func Sort[T any](enumerator Enumerator[T], less func(a, b T) bool) Enumerator[T] {
slice, err := ToSlice(enumerator)
if err != nil {
return Generate(func() (T, bool, error) {
return *new(T), false, err
})
}
sort.Slice(slice, func(i, j int) bool {
return less(slice[i], slice[j])
})
return Slice(slice)
}
// Reverse reverses the order of elements in the enumerator.
// The enumerator is consumed eagerly, then returned as a new enumerator in reverse order.
func Reverse[T any](enumerator Enumerator[T]) Enumerator[T] {
slice, err := ToSlice(enumerator)
if err != nil {
return Generate(func() (T, bool, error) {
return *new(T), false, err
})
}
for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
slice[i], slice[j] = slice[j], slice[i]
}
return Slice(slice)
}