0
0
mirror of https://github.com/thegeeklab/wp-plugin-go.git synced 2024-06-03 04:49:41 +02:00
wp-plugin-go/slice/slice.go

45 lines
744 B
Go
Raw Normal View History

2024-03-11 11:57:11 +01:00
package slice
// SetDifference returns a slice containing the elements in slice a that are not in slice b.
func SetDifference[T comparable](a, b []T, unique bool) []T {
result := make([]T, 0)
if unique {
a = Unique(a)
}
for _, aItem := range a {
found := false
for _, bItem := range b {
if aItem == bItem {
found = true
break
}
}
if !found {
result = append(result, aItem)
}
}
return result
}
// Unique returns a slice containing only the unique elements of the given slice.
func Unique[T comparable](s []T) []T {
seen := make(map[T]struct{})
result := make([]T, 0)
for _, v := range s {
if _, ok := seen[v]; !ok {
seen[v] = struct{}{}
result = append(result, v)
}
}
return result
}