// 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" "git.portale-stac.it/go-pkg/expr/scan" ) //-------- group by term func newGroupByTerm(tk *scan.Token) (inst *scan.Term) { return &scan.Term{ Tk: *tk, Children: make([]*scan.Term, 0, 2), Position: scan.PosInfix, Priority: scan.PriIterOp, EvalFunc: evalGroupBy, } } func evalGroupBy(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) { var leftValue, rightValue any var it kern.Iterator var item any var sKey string var keyByIndex bool var ok bool if err = opTerm.CheckOperands(); err != nil { return } if leftValue, err = opTerm.Children[0].Compute(ctx); err != nil { return } if it, ok = leftValue.(kern.Iterator); !ok { if it, err = NewIterator(ctx, leftValue, nil); 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(scan.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() { scan.RegisterTermConstructor(scan.SymKwGroupBy, newGroupByTerm) }