alist/pkg/utils/slice.go

63 lines
1.2 KiB
Go
Raw Normal View History

package utils
import (
"strings"
"github.com/pkg/errors"
)
2022-08-07 16:51:05 +00:00
// SliceEqual check if two slices are equal
func SliceEqual[T comparable](a, b []T) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
2022-06-23 13:19:01 +00:00
2022-08-07 16:51:05 +00:00
// SliceContains check if slice contains element
2022-06-23 13:19:01 +00:00
func SliceContains[T comparable](arr []T, v T) bool {
for _, vv := range arr {
if vv == v {
return true
}
}
return false
}
2022-07-27 09:08:29 +00:00
2022-08-07 16:51:05 +00:00
// SliceConvert convert slice to another type slice
2022-07-27 09:08:29 +00:00
func SliceConvert[S any, D any](srcS []S, convert func(src S) (D, error)) ([]D, error) {
res := make([]D, 0, len(srcS))
2022-08-07 16:51:05 +00:00
for i := range srcS {
2022-07-27 09:08:29 +00:00
dst, err := convert(srcS[i])
if err != nil {
return nil, err
}
res = append(res, dst)
}
return res, nil
}
func MustSliceConvert[S any, D any](srcS []S, convert func(src S) D) []D {
res := make([]D, 0, len(srcS))
for i := range srcS {
dst := convert(srcS[i])
res = append(res, dst)
}
return res
}
func MergeErrors(errs ...error) error {
errStr := strings.Join(MustSliceConvert(errs, func(err error) string {
return err.Error()
}), "\n")
if errStr != "" {
return errors.New(errStr)
}
return nil
}