From f285d1f8e00405771e647fc3fa615d132340b28f Mon Sep 17 00:00:00 2001 From: Leon Mika Date: Thu, 19 Jun 2025 13:20:29 +0200 Subject: [PATCH] Add MaxIndex function --- moslice/map.go | 13 +++++++++++++ moslice/map_test.go | 20 +++++++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/moslice/map.go b/moslice/map.go index 78a9451..73fd2eb 100644 --- a/moslice/map.go +++ b/moslice/map.go @@ -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. diff --git a/moslice/map_test.go b/moslice/map_test.go index d15bf7d..4270c19 100644 --- a/moslice/map_test.go +++ b/moslice/map_test.go @@ -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}