-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdotnotation.go
More file actions
116 lines (101 loc) · 2.38 KB
/
dotnotation.go
File metadata and controls
116 lines (101 loc) · 2.38 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package dotnotation
import (
"errors"
"strconv"
"strings"
)
type fieldType uint8
const (
stringType fieldType = iota
numericType
wildcardType
)
type step struct {
ft fieldType
key string
index int
}
func compile(expr string, op func(interface{}) interface{}) (*dotNotation, error) {
if expr == "" {
return nil, errors.New("cannot compile empty expr")
}
parts := strings.Split(expr, ".")
steps := make([]step, 0, len(parts))
wc := 0
for _, p := range parts {
idx, err := strconv.Atoi(p)
isIndex := err == nil && idx >= 0
switch {
case p == "":
return nil, errors.New("found empty field on expresion " + expr)
case p == "*":
wc++
steps = append(steps, step{ft: wildcardType})
case isIndex:
steps = append(steps, step{ft: numericType, index: idx, key: p})
default:
steps = append(steps, step{ft: stringType, key: p})
}
}
// if there's a wildcard on last step, we remove it from counter so it goes through Linear paths anyway
// since it does not need to allocate a slice while traversing the main path
if steps[len(steps)-1].ft == wildcardType {
wc--
}
var applyStep step
if op != nil {
applyStep = steps[len(steps)-1]
steps = steps[:len(steps)-1]
}
return &dotNotation{
extractSteps: steps,
applyStep: applyStep,
op: op,
wc: wc,
}, nil
}
type dotNotation struct {
extractSteps []step
applyStep step
op func(interface{}) interface{}
wc int
}
func wildcardTraverse(current []interface{}, next []interface{}) []interface{} {
for _, n := range current {
switch v := n.(type) {
case []interface{}:
next = append(next, v...)
case map[string]interface{}:
for _, vv := range v {
next = append(next, vv)
}
}
}
return next
}
func numericTraverse(current []interface{}, step step, next []interface{}) []interface{} {
for _, n := range current {
if m, ok := n.(map[string]interface{}); ok {
if v, exists := m[step.key]; exists {
next = append(next, v)
}
continue
}
if arr, ok := n.([]interface{}); ok {
if step.index < len(arr) {
next = append(next, arr[step.index])
}
}
}
return next
}
func stringTraverse(current []interface{}, step step, next []interface{}) []interface{} {
for _, n := range current {
if m, ok := n.(map[string]interface{}); ok {
if v, exists := m[step.key]; exists {
next = append(next, v)
}
}
}
return next
}