106 lines
2.3 KiB
Go
106 lines
2.3 KiB
Go
// Copyright (c) 2024-2026 Celestino Amoroso (celestino.amoroso@gmail.com).
|
|
// All rights reserved.
|
|
|
|
// operator-groupby.go
|
|
package expr
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"strconv"
|
|
|
|
"git.portale-stac.it/go-pkg/expr/kern"
|
|
)
|
|
|
|
//-------- group by term
|
|
|
|
func newGroupByTerm(tk *Token) (inst *term) {
|
|
return &term{
|
|
tk: *tk,
|
|
children: make([]*term, 0, 2),
|
|
position: posInfix,
|
|
priority: priIterOp,
|
|
evalFunc: evalGroupBy,
|
|
}
|
|
}
|
|
|
|
func evalGroupBy(ctx kern.ExprContext, opTerm *term) (v any, err error) {
|
|
var leftValue, rightValue any
|
|
var it kern.Iterator
|
|
var item any
|
|
var sKey string
|
|
var keyByIndex bool
|
|
|
|
if err = opTerm.checkOperands(); err != nil {
|
|
return
|
|
}
|
|
|
|
if leftValue, err = opTerm.children[0].Compute(ctx); err != nil {
|
|
return
|
|
}
|
|
|
|
if it, err = NewIterator(leftValue); err != nil {
|
|
return nil, fmt.Errorf("left operand of MAP must be an iterable data-source; got %s", kern.TypeName(leftValue))
|
|
}
|
|
|
|
rightTk := opTerm.children[1].tk
|
|
if rightTk.IsSymbol(SymVariable) && rightTk.source == "__" {
|
|
keyByIndex = true
|
|
} else if rightValue, err = opTerm.children[1].Compute(ctx); err != nil {
|
|
return
|
|
} else if kern.IsString(rightValue) {
|
|
sKey = rightValue.(string)
|
|
} else {
|
|
return nil, fmt.Errorf("right operand of GROUPBY must be a string or identifier '__'; got %s", kern.TypeName(rightValue))
|
|
}
|
|
|
|
values := kern.MakeDict()
|
|
for item, err = it.Next(); err == nil; item, err = it.Next() {
|
|
ctx.SetVar("_", item)
|
|
ctx.SetVar("__", it.Index())
|
|
ctx.SetVar("_#", it.Count())
|
|
|
|
var sItemKey string
|
|
|
|
if d, ok := item.(*kern.DictType); ok {
|
|
if keyByIndex || len(sKey) == 0 {
|
|
sItemKey = strconv.Itoa(int(it.Index()))
|
|
} else if d.HasKey(sKey) {
|
|
if keyValue, exists := d.GetItem(sKey); exists {
|
|
sItemKey = fmt.Sprintf("%v", keyValue)
|
|
} else {
|
|
sItemKey = "_"
|
|
}
|
|
} else {
|
|
sItemKey = "_"
|
|
}
|
|
} else {
|
|
sItemKey = strconv.Itoa(int(it.Index()))
|
|
}
|
|
|
|
var ls *kern.ListType
|
|
if lsAny, exists := values.GetItem(sItemKey); exists && lsAny != nil {
|
|
ls = lsAny.(*kern.ListType)
|
|
}
|
|
if ls == nil {
|
|
ls = kern.NewListA()
|
|
}
|
|
ls.AppendItem(item)
|
|
values.SetItem(sItemKey, ls)
|
|
|
|
ctx.DeleteVar("_#")
|
|
ctx.DeleteVar("__")
|
|
ctx.DeleteVar("_")
|
|
}
|
|
if err == io.EOF {
|
|
err = nil
|
|
}
|
|
v = values
|
|
return
|
|
}
|
|
|
|
// init
|
|
func init() {
|
|
registerTermConstructor(SymKwGroupBy, newGroupByTerm)
|
|
}
|