-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpipe.go
More file actions
83 lines (66 loc) · 1.93 KB
/
pipe.go
File metadata and controls
83 lines (66 loc) · 1.93 KB
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
73
74
75
76
77
78
79
80
81
82
83
package fnpipe
import (
"fmt"
"reflect"
)
// Main object of the library
// this will abstract the behavior of the whole pipeline object
type Pipe struct {
ls []interface{}
}
// Create new Pipe object by providing a list of functions
// that will be performed inside the pipeline
func NewPipeline(ls ...interface{}) (*Pipe, error) {
var pipe []interface{}
p := &Pipe{
ls: pipe,
}
for _, f := range ls {
if err := p.Add(f); err != nil {
return nil, err
}
}
return p, nil
}
// Add new function on bottom position
func (p *Pipe) Add(pf interface{}) error {
if reflect.ValueOf(pf).Type().Kind() != reflect.Func {
return fmt.Errorf("pipe func should be type Func")
}
p.ls = append(p.ls, pf)
return nil
}
// Execute the pipeline with any input, be aware that the arguments should match with the top position
// function configured with the pipeline
func (p *Pipe) ExecWith(input ...interface{}) (error, interface{}) {
var output []interface{}
for i, e := range p.ls {
output = make([]interface{}, 0)
fn := reflect.ValueOf(e)
if fn.Type().NumIn() != len(input) {
// TODO: check kind of each input to match fn definition
return fmt.Errorf("pipe: argument mismatch in pipeline func #%d", i), nil
}
// build []reflect.Value for fn input
val := make([]reflect.Value, 0)
for _, in := range input {
val = append(val, reflect.ValueOf(in))
}
// call the func
o := fn.Call(val)
for _, u := range o {
// TODO: check kind of each output to match fn definition
output = append(output, reflect.Indirect(u).Interface())
}
// pass this output to the coming next function
// if it was the last fn, we will just extract data from []reflect.Value
// in order to have concrete return value
input = output
}
values := make([]interface{}, 0)
for _, o := range output {
values = append(values, reflect.ValueOf(o).Interface())
}
// we ensure the 1st piece of the result is always the error
return nil, values
}