2024-04-17 07:12:32 +02:00
|
|
|
// 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) {
|
2024-05-04 01:23:32 +02:00
|
|
|
var childValue any
|
2024-04-17 07:12:32 +02:00
|
|
|
|
2024-05-04 01:23:32 +02:00
|
|
|
if childValue, err = self.evalPrefix(ctx); err != nil {
|
2024-04-17 07:12:32 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-08 07:53:01 +02:00
|
|
|
if IsList(childValue) {
|
2024-05-10 09:16:31 +02:00
|
|
|
ls, _ := childValue.(*ListType)
|
|
|
|
v = int64(len(*ls))
|
2024-05-08 07:53:01 +02:00
|
|
|
} else if IsString(childValue) {
|
2024-05-04 01:23:32 +02:00
|
|
|
s, _ := childValue.(string)
|
2024-04-27 22:37:56 +02:00
|
|
|
v = int64(len(s))
|
2024-05-04 01:23:32 +02:00
|
|
|
} else if it, ok := childValue.(Iterator); ok {
|
2024-05-04 08:07:49 +02:00
|
|
|
if extIt, ok := childValue.(ExtIterator); ok && extIt.HasOperation(countName) {
|
|
|
|
count, _ := extIt.CallOperation(countName, nil)
|
|
|
|
v, _ = toInt(count, "")
|
|
|
|
} else {
|
|
|
|
v = int64(it.Index() + 1)
|
|
|
|
}
|
2024-04-17 07:12:32 +02:00
|
|
|
} else {
|
2024-05-04 01:23:32 +02:00
|
|
|
err = self.errIncompatibleType(childValue)
|
2024-04-17 07:12:32 +02:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// init
|
|
|
|
func init() {
|
|
|
|
registerTermConstructor(SymHash, newLengthTerm)
|
|
|
|
}
|