goext/langext/array.go

135 lines
2.2 KiB
Go
Raw Permalink Normal View History

2022-10-27 16:00:57 +02:00
package langext
import (
"reflect"
)
func ForceArray[T any](v []T) []T {
if v == nil {
return make([]T, 0)
} else {
return v
}
}
func ReverseArray[T any](v []T) {
for i, j := 0, len(v)-1; i < j; i, j = i+1, j-1 {
v[i], v[j] = v[j], v[i]
}
}
func InArray[T comparable](needle T, haystack []T) bool {
for _, v := range haystack {
if v == needle {
return true
}
}
return false
}
func ArrUnique[T comparable](array []T) []T {
m := make(map[T]bool, len(array))
for _, v := range array {
m[v] = true
}
result := make([]T, 0, len(m))
for v := range m {
result = append(result, v)
}
return result
}
func ArrEqualsExact[T comparable](arr1 []T, arr2 []T) bool {
if len(arr1) != len(arr2) {
return false
}
for i := range arr1 {
if arr1[i] != arr2[i] {
return false
}
}
return true
}
func ArrAll(arr interface{}, fn func(int) bool) bool {
av := reflect.ValueOf(arr)
for i := 0; i < av.Len(); i++ {
if !fn(i) {
return false
}
}
return true
}
func ArrAllErr(arr interface{}, fn func(int) (bool, error)) (bool, error) {
av := reflect.ValueOf(arr)
for i := 0; i < av.Len(); i++ {
v, err := fn(i)
if err != nil {
return false, err
}
if !v {
return false, nil
}
}
return true, nil
}
func ArrNone(arr interface{}, fn func(int) bool) bool {
av := reflect.ValueOf(arr)
for i := 0; i < av.Len(); i++ {
if fn(i) {
return false
}
}
return true
}
func ArrNoneErr(arr interface{}, fn func(int) (bool, error)) (bool, error) {
av := reflect.ValueOf(arr)
for i := 0; i < av.Len(); i++ {
v, err := fn(i)
if err != nil {
return false, err
}
if v {
return false, nil
}
}
return true, nil
}
func ArrAny(arr interface{}, fn func(int) bool) bool {
av := reflect.ValueOf(arr)
for i := 0; i < av.Len(); i++ {
if fn(i) {
return true
}
}
return false
}
func ArrAnyErr(arr interface{}, fn func(int) (bool, error)) (bool, error) {
av := reflect.ValueOf(arr)
for i := 0; i < av.Len(); i++ {
v, err := fn(i)
if err != nil {
return false, err
}
if v {
return true, nil
}
}
return false, nil
}
func AddToSet[T comparable](set []T, add T) []T {
for _, v := range set {
if v == add {
return set
}
}
return append(set, add)
}