@@ -11,14 +11,23 @@ var (
11
11
12
12
// JSONLogic is an evaluator of json logic with a set of operations.
13
13
type JSONLogic struct {
14
- ops map [string ]Operation
14
+ parent * JSONLogic
15
+ ops map [string ]Operation
15
16
}
16
17
17
18
type Applier func (logic , data interface {}) (res interface {}, err error )
18
19
19
20
type Operation func (apply Applier , params []interface {}, data interface {}) (interface {}, error )
20
21
21
- // New creates a JSONLogic with standard operations.
22
+ // NewInherit creates a child JSONLogic instance.
23
+ func NewInherit (parent * JSONLogic ) * JSONLogic {
24
+ return & JSONLogic {
25
+ parent : parent ,
26
+ ops : make (map [string ]Operation ),
27
+ }
28
+ }
29
+
30
+ // New creates a root (no parent) JSONLogic with standard operations.
22
31
func New () * JSONLogic {
23
32
ret := NewEmpty ()
24
33
// Data access.
@@ -59,6 +68,7 @@ func New() *JSONLogic {
59
68
return ret
60
69
}
61
70
71
+ // NewEmpty creates a root (no parent) JSONLogic with no operation.
62
72
func NewEmpty () * JSONLogic {
63
73
return & JSONLogic {
64
74
ops : make (map [string ]Operation ),
@@ -112,7 +122,14 @@ func (jl *JSONLogic) Apply(logic, data interface{}) (res interface{}, err error)
112
122
}
113
123
}()
114
124
115
- opFn := jl .ops [op ]
125
+ var opFn Operation
126
+ for inst := jl ; inst != nil ; inst = inst .parent {
127
+ var ok bool
128
+ opFn , ok = inst .ops [op ]
129
+ if ok {
130
+ break
131
+ }
132
+ }
116
133
if opFn == nil {
117
134
return nil , fmt .Errorf ("Apply: operator %q not found" , op )
118
135
}
@@ -126,6 +143,7 @@ func AddOperation(name string, op Operation) {
126
143
}
127
144
128
145
// AddOperation adds a named operation to JSONLogic instance.
146
+ // Can override parent's same name operation.
129
147
func (jl * JSONLogic ) AddOperation (name string , op Operation ) {
130
148
jl .ops [name ] = op
131
149
}
@@ -138,7 +156,8 @@ func Clone() *JSONLogic {
138
156
// Clone clones a JSONLogic instance.
139
157
func (jl * JSONLogic ) Clone () * JSONLogic {
140
158
ret := & JSONLogic {
141
- ops : make (map [string ]Operation ),
159
+ parent : jl .parent ,
160
+ ops : make (map [string ]Operation ),
142
161
}
143
162
for k , v := range jl .ops {
144
163
ret .ops [k ] = v
0 commit comments