modash/moslice/map_test.go

77 lines
1.7 KiB
Go
Raw Normal View History

package moslice_test
import (
"errors"
"testing"
2025-06-19 11:20:29 +00:00
"lmika.dev/pkg/modash/moslice"
"github.com/stretchr/testify/assert"
)
func TestMap(t *testing.T) {
t.Run("should return a mapped slice", func(t *testing.T) {
ts := []int{1, 2, 3}
us := moslice.Map(ts, func(x int) int { return x + 2 })
assert.Equal(t, []int{3, 4, 5}, us)
})
t.Run("should return nil if passed in nil", func(t *testing.T) {
ts := []int(nil)
us := moslice.Map(ts, func(x int) int { return x + 2 })
assert.Nil(t, us)
})
}
2025-06-19 11:20:29 +00:00
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}
us, err := moslice.MapWithError(ts, func(x int) (int, error) { return x + 2, nil })
assert.Equal(t, []int{3, 4, 5}, us)
assert.NoError(t, err)
})
t.Run("should return nil with an error when mapping function returns an error", func(t *testing.T) {
ts := []int{1, 2, 3}
us, err := moslice.MapWithError(ts, func(x int) (int, error) {
if x == 2 {
return 0, errors.New("bang")
}
return x + 2, nil
})
assert.Nil(t, us)
assert.Error(t, err)
})
t.Run("should return nil if passed in nil", func(t *testing.T) {
ts := []int(nil)
us, err := moslice.MapWithError(ts, func(x int) (int, error) { return x + 2, nil })
assert.Nil(t, us)
assert.NoError(t, err)
})
}