-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmap_slice.go
More file actions
32 lines (25 loc) · 768 Bytes
/
map_slice.go
File metadata and controls
32 lines (25 loc) · 768 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package pipe
import (
"fmt"
"reflect"
)
// MapSlice is of type: func(fn func(T) U, input []T) []U.
// It returns a slice of fn(item) for each item in input.
func MapSlice(fn, input interface{}) interface{} {
checkMapFuncType(fn, input)
inputValue := reflect.ValueOf(input)
fnValue := reflect.ValueOf(fn)
if inputValue.Kind() != reflect.Slice &&
inputValue.Kind() != reflect.Array {
panic(fmt.Sprintf("MapSlice called on invalid type: %s", inputValue.Type()))
}
outputType := reflect.SliceOf(fnValue.Type().Out(0))
output := reflect.MakeSlice(outputType, 0, inputValue.Len())
for i := 0; i < inputValue.Len(); i++ {
output = reflect.Append(
output,
fnValue.Call([]reflect.Value{inputValue.Index(i)})[0],
)
}
return output.Interface()
}