ArrFirstIndex, ArrLastIndex, ArrMap, ArrSum

This commit is contained in:
Mike Schwörer 2022-11-14 20:42:50 +01:00
parent 93be4f9fdd
commit b643bded8a
Signed by: Mikescher
GPG Key ID: D3C7172E0A70F8CF

View File

@ -163,6 +163,25 @@ func ArrLast[T comparable](arr []T, comp func(v T) bool) (T, bool) {
return result, found
}
func ArrFirstIndex[T comparable](arr []T, needle T) int {
for i, v := range arr {
if v == needle {
return i
}
}
return -1
}
func ArrLastIndex[T comparable](arr []T, needle T) int {
result := -1
for i, v := range arr {
if v == needle {
result = i
}
}
return result
}
func AddToSet[T comparable](set []T, add T) []T {
for _, v := range set {
if v == add {
@ -171,3 +190,19 @@ func AddToSet[T comparable](set []T, add T) []T {
}
return append(set, add)
}
func ArrMap[T1 any, T2 any](arr []T1, conv func(v T1) T2) []T2 {
r := make([]T2, len(arr))
for i, v := range arr {
r[i] = conv(v)
}
return r
}
func ArrSum[T NumberConstraint](arr []T) T {
var r T = 0
for _, v := range arr {
r += v
}
return r
}