Add MaxIndex function
All checks were successful
ci / deploy (push) Successful in 1m2s

This commit is contained in:
Leon Mika 2025-06-19 13:20:29 +02:00
parent c73e50a091
commit f285d1f8e0
2 changed files with 32 additions and 1 deletions

View file

@ -13,6 +13,19 @@ func Map[T, U any](ts []T, fn func(t T) U) (us []U) {
return us
}
// Map returns a new slice containing the elements of ts transformed by the passed in function.
func MapIndex[T, U any](ts []T, fn func(t T, index int) U) (us []U) {
if ts == nil {
return nil
}
us = make([]U, len(ts))
for i, t := range ts {
us[i] = fn(t, i)
}
return us
}
// Map returns a new slice containing the elements of ts transformed by the passed in function, which
// can either either a mapped value of U, or an error. If the mapping function returns an error, MapWithError
// will return nil and the returned error.

View file

@ -2,9 +2,10 @@ package moslice_test
import (
"errors"
"lmika.dev/pkg/modash/moslice"
"testing"
"lmika.dev/pkg/modash/moslice"
"github.com/stretchr/testify/assert"
)
@ -24,6 +25,23 @@ func TestMap(t *testing.T) {
})
}
func TestMapIndex(t *testing.T) {
t.Run("should return a map and index slice", func(t *testing.T) {
ts := []int{1, 2, 3}
us := moslice.MapIndex(ts, func(_ int, i int) int { return i })
assert.Equal(t, []int{0, 1, 2}, us)
})
t.Run("should return nil if passed in nil", func(t *testing.T) {
ts := []int(nil)
us := moslice.MapIndex(ts, func(_, i int) int { return i })
assert.Nil(t, us)
})
}
func TestMapWithError(t *testing.T) {
t.Run("should return a mapped slice with no error", func(t *testing.T) {
ts := []int{1, 2, 3}