-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathslice_subset.go
88 lines (82 loc) · 1.69 KB
/
slice_subset.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
package gofn
// ContainSlice tests if a slice contains a slice
func ContainSlice[T comparable, S ~[]T](a, b S) bool {
return IndexOfSlice(a, b) >= 0
}
// IndexOfSlice gets index of sub-slice in slice.
// Returns -1 if not found.
func IndexOfSlice[T comparable, S ~[]T](a, sub S) int {
lengthA := len(a)
lengthSub := len(sub)
if lengthSub == 0 || lengthA < lengthSub {
return -1
}
sub1st := sub[0]
for i, max := 0, lengthA-lengthSub; i <= max; i++ {
if a[i] == sub1st {
found := true
for j := 1; j < lengthSub; j++ {
if a[i+j] != sub[j] {
found = false
break
}
}
if found {
return i
}
}
}
return -1
}
// LastIndexOfSlice gets last index of sub-slice in slice
// Returns -1 if not found
func LastIndexOfSlice[T comparable, S ~[]T](a, sub S) int {
lengthA := len(a)
lengthSub := len(sub)
if lengthSub == 0 || lengthA < lengthSub {
return -1
}
sub1st := sub[0]
for i := lengthA - lengthSub; i >= 0; i-- {
if a[i] == sub1st {
found := true
for j := 1; j < lengthSub; j++ {
if a[i+j] != sub[j] {
found = false
break
}
}
if found {
return i
}
}
}
return -1
}
// SubSlice gets sub slice from a slice.
// Passing negative numbers to get items from the end of the slice.
// For example, using start=-1, end=-2 to get the last item of the slice
// end param is exclusive.
func SubSlice[T any, S ~[]T](s S, start, end int) S {
length := len(s)
if length == 0 {
return S{}
}
for start < 0 {
start += length
}
if start > length {
start = length
}
for end < 0 {
end += length
}
if end > length {
end = length
}
if start > end {
// NOTE: end is exclusive
return s[end+1 : start+1]
}
return s[start:end]
}