-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathslice.go
90 lines (80 loc) · 2.19 KB
/
slice.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//go:build go1.18
// +build go1.18
package sliceext
import (
"sort"
optionext "github.com/go-playground/pkg/v5/values/option"
)
// Retain retains only the elements specified by the function.
//
// This returns a new slice with references to the underlying data instead of shuffling.
func Retain[T any](slice []T, fn func(v T) bool) []T {
results := make([]T, 0, len(slice))
for _, v := range slice {
v := v
if fn(v) {
results = append(results, v)
}
}
return results
}
// Filter filters out the elements specified by the function.
//
// This returns a new slice with references to the underlying data instead of shuffling.
func Filter[T any](slice []T, fn func(v T) bool) []T {
results := make([]T, 0, len(slice))
for _, v := range slice {
v := v
if fn(v) {
continue
}
results = append(results, v)
}
return results
}
// Map maps a slice of []T -> []U using the map function.
func Map[T, U any](slice []T, init U, fn func(accum U, v T) U) U {
if len(slice) == 0 {
return init
}
accum := init
for _, v := range slice {
accum = fn(accum, v)
}
return accum
}
// Sort sorts the sliceWrapper x given the provided less function.
//
// The sort is not guaranteed to be stable: equal elements
// may be reversed from their original order.
//
// For a stable sort, use SortStable.
func Sort[T any](slice []T, less func(i T, j T) bool) {
sort.Slice(slice, func(j, k int) bool {
return less(slice[j], slice[k])
})
}
// SortStable sorts the sliceWrapper x using the provided less
// function, keeping equal elements in their original order.
func SortStable[T any](slice []T, less func(i T, j T) bool) {
sort.SliceStable(slice, func(j, k int) bool {
return less(slice[j], slice[k])
})
}
// Reduce reduces the elements to a single one, by repeatedly applying a reducing function.
func Reduce[T any](slice []T, fn func(accum T, current T) T) optionext.Option[T] {
if len(slice) == 0 {
return optionext.None[T]()
}
accum := slice[0]
for _, v := range slice {
accum = fn(accum, v)
}
return optionext.Some(accum)
}
// Reverse reverses the slice contents.
func Reverse[T any](slice []T) {
for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
slice[i], slice[j] = slice[j], slice[i]
}
}