forked from expr-lang/expr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter_first.go
38 lines (35 loc) · 1.01 KB
/
filter_first.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
package optimizer
import (
. "github.com/antonmedv/expr/ast"
)
type filterFirst struct{}
func (*filterFirst) Visit(node *Node) {
if member, ok := (*node).(*MemberNode); ok && member.Property != nil && !member.Optional {
if prop, ok := member.Property.(*IntegerNode); ok && prop.Value == 0 {
if filter, ok := member.Node.(*BuiltinNode); ok &&
filter.Name == "filter" &&
len(filter.Arguments) == 2 {
Patch(node, &BuiltinNode{
Name: "find",
Arguments: filter.Arguments,
Throws: true, // to match the behavior of filter()[0]
Map: filter.Map,
})
}
}
}
if first, ok := (*node).(*BuiltinNode); ok &&
first.Name == "first" &&
len(first.Arguments) == 1 {
if filter, ok := first.Arguments[0].(*BuiltinNode); ok &&
filter.Name == "filter" &&
len(filter.Arguments) == 2 {
Patch(node, &BuiltinNode{
Name: "find",
Arguments: filter.Arguments,
Throws: false, // as first() will return nil if not found
Map: filter.Map,
})
}
}
}