/
slice.go
40 lines (36 loc) · 950 Bytes
/
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
package helpers
// HasDuplicates checks if the provided slice contains any duplicate elements.
// It accepts a slice of any comparable type and returns true if there are duplicates, otherwise it returns false.
func HasDuplicates[T comparable](slice []T) bool {
seen := make(map[T]bool)
for _, v := range slice {
if seen[v] {
return true
}
seen[v] = true
}
return false
}
// IsSubset checks if all elements of sliceA are also present in sliceB.
// It returns true if sliceA is a subset of sliceB, otherwise it returns false.
func IsSubset[T comparable](sliceA, sliceB []T) bool {
setB := make(map[T]bool)
for _, v := range sliceB {
setB[v] = true
}
for _, v := range sliceA {
if !setB[v] {
return false
}
}
return true
}
// Contains checks if the slice contains the given value.
func Contains[T comparable](value T, sliceB []T) bool {
for _, v := range sliceB {
if v == value {
return true
}
}
return false
}