/
slice_helper.go
50 lines (44 loc) · 1018 Bytes
/
slice_helper.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
package utils
import (
"sort"
"golang.org/x/exp/constraints"
)
// SortSlice sorts a slice of type T elements that implement constraints.Ordered.
// Mutates input slice s
func SortSlice[T constraints.Ordered](s []T) {
sort.Slice(s, func(i, j int) bool {
return s[i] < s[j]
})
}
func Filter[T interface{}](filter func(T) bool, s []T) []T {
filteredSlice := []T{}
for _, s := range s {
if filter(s) {
filteredSlice = append(filteredSlice, s)
}
}
return filteredSlice
}
// ReverseSlice reverses the input slice in place.
// Does mutate argument.
func ReverseSlice[T any](s []T) []T {
maxIndex := len(s)
for i := 0; i < maxIndex/2; i++ {
temp := s[i]
s[i] = s[maxIndex-i-1]
s[maxIndex-1-i] = temp
}
return s
}
// ContainsDuplicate checks if there are any duplicate
// elements in the slice.
func ContainsDuplicate[T any](arr []T) bool {
visited := make(map[any]bool, 0)
for i := 0; i < len(arr); i++ {
if visited[arr[i]] {
return true
}
visited[arr[i]] = true
}
return false
}