goutils/sliceutils/sliceUtils.go

91 lines
1.9 KiB
Go
Raw Normal View History

2023-08-18 15:13:53 +00:00
package sliceutils
// MapS applies a given function to every element of a slice.
2023-08-18 15:13:53 +00:00
// The return type may be different from the initial type of the slice.
func Map[T any, M any](arr []T, apply func(T) M) []M {
2023-08-18 15:13:53 +00:00
n := make([]M, len(arr))
for i, e := range arr {
n[i] = apply(e)
}
return n
}
// Filter filters a slice using a given function.
2023-08-18 15:13:53 +00:00
// If the filter function returns true, the element stays, otherwise it gets removed.
func Filter[T any](arr []T, filter func(T) bool) []T {
2023-08-18 15:13:53 +00:00
n := make([]T, 0)
for _, e := range arr {
if filter(e) {
n = append(n, e)
}
}
return n
}
// RemoveDuplicate removes all duplicates inside a slice.
func RemoveDuplicate[T comparable](sliceList []T) []T {
2023-08-18 15:13:53 +00:00
allKeys := make(map[T]bool)
list := []T{}
for _, item := range sliceList {
if _, value := allKeys[item]; !value {
allKeys[item] = true
list = append(list, item)
}
}
return list
}
// Reverse reverses a given slice.
func Reverse[E any](s []E) {
2023-08-18 15:13:53 +00:00
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
// CompareOrdered compares two slices for both element equality and element order.
func CompareOrdered[T comparable](a, b []T) bool {
2023-08-18 15:13:53 +00:00
if len(a) != len(b) {
return false
}
for i, v := range a {
if b[i] != v {
return false
}
}
return true
}
// CompareUnorderedS compares two slices for element equality.
2023-08-18 15:13:53 +00:00
// The order of those elements does not matter.
func CompareUnordered[T comparable](a, b []T) bool {
2023-08-18 15:13:53 +00:00
if len(a) != len(b) {
return false
}
hits := 0
for _, v := range a {
for _, o := range b {
if o == v {
hits += 1
}
}
}
return hits == len(a)
}
func Contains[T comparable](a []T, b T) bool {
for _, v := range a {
if v == b {
return true
}
}
return false
}
2024-12-01 09:29:28 +00:00
func Compact[T any](a []T, compactor func(acc T, next T) T) T {
var acc T
for _, v := range a {
acc = compactor(acc, v)
}
return acc
}