44 lines
880 B
Go
44 lines
880 B
Go
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
|
|
// All rights reserved.
|
|
|
|
// operator-length.go
|
|
package expr
|
|
|
|
//-------- length term
|
|
|
|
func newLengthTerm(tk *Token) (inst *term) {
|
|
return &term{
|
|
tk: *tk,
|
|
children: make([]*term, 0, 1),
|
|
position: posPrefix,
|
|
priority: priSign,
|
|
evalFunc: evalLength,
|
|
}
|
|
}
|
|
|
|
func evalLength(ctx ExprContext, self *term) (v any, err error) {
|
|
var childValue any
|
|
|
|
if childValue, err = self.evalPrefix(ctx); err != nil {
|
|
return
|
|
}
|
|
|
|
if isList(childValue) {
|
|
list, _ := childValue.([]any)
|
|
v = int64(len(list))
|
|
} else if isString(childValue) {
|
|
s, _ := childValue.(string)
|
|
v = int64(len(s))
|
|
} else if it, ok := childValue.(Iterator); ok {
|
|
v = int64(it.Index() + 1)
|
|
} else {
|
|
err = self.errIncompatibleType(childValue)
|
|
}
|
|
return
|
|
}
|
|
|
|
// init
|
|
func init() {
|
|
registerTermConstructor(SymHash, newLengthTerm)
|
|
}
|