From b643bded8a71a67dc7152c77b852893b55ba6c79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Mon, 14 Nov 2022 20:42:50 +0100 Subject: [PATCH] ArrFirstIndex, ArrLastIndex, ArrMap, ArrSum --- langext/array.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/langext/array.go b/langext/array.go index 430ef45..053d618 100644 --- a/langext/array.go +++ b/langext/array.go @@ -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 +}