/
only_expr.go
40 lines (31 loc) 路 943 Bytes
/
only_expr.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
package q
import (
"errors"
"reflect"
)
// OnlyExpr is a function. See Evaluate.
type OnlyExpr struct{}
// Evaluate returns a new slice that only contains the entities that have
// returned true from the condition.
func (e *OnlyExpr) Evaluate(engine *Engine, input interface{}, args []*Statement) (interface{}, error) {
in := reflect.ValueOf(input)
if len(args) != 1 {
return nil, errors.New("function Only() must take a single argument")
}
if in.Kind() != reflect.Slice {
return nil, nil
}
inputSliceType := TypeOfSliceElement(input)
results := reflect.MakeSlice(reflect.SliceOf(inputSliceType), 0, 0)
condition := args[0]
for i := 0; i < in.Len(); i++ {
result, err := condition.Evaluate(engine, in.Index(i).Interface())
if err != nil {
return nil, err
}
if shouldAppend, ok := result.(bool); ok && shouldAppend {
results = reflect.Append(results, in.Index(i))
}
}
return results.Interface(), nil
}