new operator 'in' added. It check if an item is member of a list, or if a key is contained in a dictionary
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
|
||||
// All rights reserved.
|
||||
|
||||
// operator-in.go
|
||||
package expr
|
||||
|
||||
//-------- in term
|
||||
|
||||
func newInTerm(tk *Token) (inst *term) {
|
||||
return &term{
|
||||
tk: *tk,
|
||||
children: make([]*term, 0, 2),
|
||||
position: posInfix,
|
||||
priority: priRelational,
|
||||
evalFunc: evalIn,
|
||||
}
|
||||
}
|
||||
|
||||
func hasKey(d map[any]any, target any) (ok bool) {
|
||||
_, ok = d[target]
|
||||
return
|
||||
}
|
||||
|
||||
func evalIn(ctx ExprContext, self *term) (v any, err error) {
|
||||
var leftValue, rightValue any
|
||||
|
||||
if leftValue, rightValue, err = self.evalInfix(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if IsList(rightValue) {
|
||||
list, _ := rightValue.(*ListType)
|
||||
v = list.indexDeepCmp(leftValue) >= 0
|
||||
} else if IsDict(rightValue) {
|
||||
d, _ := rightValue.(map[any]any)
|
||||
v = hasKey(d, leftValue)
|
||||
} else {
|
||||
err = self.errIncompatibleTypes(leftValue, rightValue)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// init
|
||||
func init() {
|
||||
registerTermConstructor(SymKwIn, newInTerm)
|
||||
}
|
||||
Reference in New Issue
Block a user