Skip to content

Commit 48e4ef7

Browse files
committed
Add validation for mapper function return type
Signed-off-by: Dinesh <dineshudt17@gmail.com>
1 parent a401794 commit 48e4ef7

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

map.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,15 @@ func Map(in, out, mapperFn interface{}) error {
2828
}
2929

3030
if input.Kind() == reflect.Slice {
31+
if output.Kind() != reflect.Slice {
32+
return fmt.Errorf("output should be a slice for input of type slice")
33+
}
3134
if input.Type().Elem().Kind() != mapper.Type().In(0).Kind() {
3235
return fmt.Errorf("mapper function's first argument has to be the type of element of input slice")
3336
}
37+
if output.Type().Elem().Elem().Kind() != mapper.Type().Out(0).Kind() {
38+
return fmt.Errorf("mapper function's return type has to be the type of element of output slice")
39+
}
3440

3541
result := reflect.MakeSlice(output.Elem().Type(), 0, input.Len())
3642
for i := 0; i < input.Len(); i++ {
@@ -46,4 +52,3 @@ func Map(in, out, mapperFn interface{}) error {
4652
}
4753
return fmt.Errorf("not implemented")
4854
}
49-

map_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,15 @@ func TestMap(t *testing.T) {
6262
}
6363
})
6464

65+
t.Run("should not panic if output is not a slice", func(t *testing.T) {
66+
in := []int{1, 2, 3}
67+
var out int
68+
69+
err := godash.Map(in, &out, squared)
70+
71+
assert.EqualError(t, err, "output should be a slice for input of type slice")
72+
})
73+
6574
t.Run("should not accept mapper function that are not functions", func(t *testing.T) {
6675
in := []int{1, 2, 3}
6776
var out []int
@@ -115,4 +124,19 @@ func TestMap(t *testing.T) {
115124
assert.NoError(t, err)
116125
}
117126
})
127+
128+
t.Run("should accept mapper function whose return's kind should be output slice's element kind", func(t *testing.T) {
129+
in := []int{1, 2, 3}
130+
var out []string
131+
132+
{
133+
err := godash.Map(in, &out, func(int) int { return 0 })
134+
assert.EqualError(t, err, "mapper function's return type has to be the type of element of output slice")
135+
}
136+
137+
{
138+
err := godash.Map(in, &out, func(int) string { return "" })
139+
assert.NoError(t, err)
140+
}
141+
})
118142
}

0 commit comments

Comments
 (0)