package sliceutils // MapSlice applies a given function to every element of a slice. // The return type may be different from the initial type of the slice. func MapSlice[T any, M any](arr []T, apply func(T) M) []M { n := make([]M, len(arr)) for i, e := range arr { n[i] = apply(e) } return n } // FilterSlice filters a slice using a given function. // If the filter function returns true, the element stays, otherwise it gets removed. func FilterSlice[T any](arr []T, filter func(T) bool) []T { n := make([]T, 0) for _, e := range arr { if filter(e) { n = append(n, e) } } return n } // RemoveDuplicateSlice removes all duplicates inside a slice. func RemoveDuplicateSlice[T comparable](sliceList []T) []T { 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 } // ReverseSlice reverses a given slice. func ReverseSlice[S ~[]E, E any](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] } } // CompareOrderedSlice compares two slices for both element equality and element order. func CompareOrderedSlice[T comparable](a, b []T) bool { if len(a) != len(b) { return false } for i, v := range a { if b[i] != v { return false } } return true } // CompareUnorderedSlice compares two slices for element equality. // The order of those elements does not matter. func CompareUnorderedSlice[T comparable](a, b []T) bool { 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) }