-
Notifications
You must be signed in to change notification settings - Fork 0
/
compose.go
72 lines (56 loc) · 1.63 KB
/
compose.go
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package functools
import (
"reflect"
"errors"
"strconv"
)
/*
'Compose' allows to pipe unlimited number of functions to one composed 'func'.
Compose(fs...) func(args...) interface{}
ComposeSafe(fs...) (func(args...) interface{}, err)
*/
func compose(functions ...interface{}) func(...interface{}) interface{} {
for i, fn := range functions {
if reflect.ValueOf(fn).Kind() != reflect.Func {
raise(errors.New("Param " + strconv.Itoa(i) + " isn't a function"), "Compose")
}
}
for i := 0; i < len(functions) - 1; i++ {
fnA := reflect.ValueOf(functions[i])
fnB := reflect.ValueOf(functions[i + 1])
if !canPipe(fnA, fnB) {
raise(errors.New("Function " + strconv.Itoa(i) + " and " +
strconv.Itoa(i + 1) + " cannot be piped"), "Compose")
}
}
composedFunc := func(in ...interface{}) interface{} {
params := make([]reflect.Value, 0, len(in))
for _, v := range in {
params = append(params, reflect.ValueOf(v))
}
for i := 0; i < len(functions); i++ {
params = reflect.ValueOf(functions[i]).Call(params[:])
}
return params[0].Interface()
}
return composedFunc
}
func canPipe(fnA, fnB reflect.Value) bool {
if fnA.Type().NumOut() != fnB.Type().NumIn() {
return false
}
for i := 0; i < fnA.Type().NumOut(); i++ {
if fnA.Type().Out(i) != fnB.Type().In(i) && fnB.Type().In(i).Kind() != reflect.Interface {
return false
}
}
return true
}
func Compose(functions ...interface{}) func(...interface{}) interface{} {
return compose(functions...)
}
func ComposeSafe(functions ...interface{}) (result func(...interface{}) interface{}, err error) {
defer except(&err)
result = compose(functions...)
return
}