-
Notifications
You must be signed in to change notification settings - Fork 0
/
slices.go
69 lines (56 loc) · 1.4 KB
/
slices.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
package books
// RemoveDupes removes duplicates from a slice, order is preserved.
func RemoveDupes[T comparable, S ~[]T](s S) S {
m := make(map[T]struct{})
idx := 0
// If an item has not been seen before, adding it in-place and incrementing the index
for i := range s {
if _, ok := m[s[i]]; !ok {
m[s[i]] = struct{}{}
s[idx] = s[i]
idx++
}
}
return s[:idx]
}
// ReverseSlice reverses the order of the elements in the array passed.
func ReverseSlice[T any, S ~[]T](s S) S {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
return s
}
// Contains checks if the slice contains the given element.
func Contains[T comparable, S ~[]T](s S, e T) bool {
for i := range s {
if e == s[i] {
return true
}
}
return false
}
// FilterSlice filters a slice by passed function.
// The passed function should return true to keep item, and false to remove it.
func FilterSlice[T any, S ~[]T](s S, f func(T) bool) S {
idx := 0
for i := range s {
if f(s[i]) {
s[idx] = s[i]
idx++
}
}
return s[:idx]
}
// EqualSlices checks if two slices of comparable types are equal.
// From personal testing, this seems to be faster than reflect.DeepEqual(), but this has not been tested thoroughly.
func EqualSlices[T comparable, S ~[]T](s1, s2 S) bool {
if len(s1) != len(s2) {
return false
}
for i := range s1 {
if s1[i] != s2[i] {
return false
}
}
return true
}