2021-10-26 04:42:25 +00:00
|
|
|
package yqlib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
|
|
|
type flattenPreferences struct {
|
|
|
|
depth int
|
|
|
|
}
|
|
|
|
|
2023-10-18 01:11:53 +00:00
|
|
|
func flatten(node *CandidateNode, depth int) {
|
2021-10-26 04:42:25 +00:00
|
|
|
if depth == 0 {
|
|
|
|
return
|
|
|
|
}
|
2023-10-18 01:11:53 +00:00
|
|
|
if node.Kind != SequenceNode {
|
2021-10-26 04:42:25 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
content := node.Content
|
2023-10-18 01:11:53 +00:00
|
|
|
newSeq := make([]*CandidateNode, 0)
|
2021-10-26 04:42:25 +00:00
|
|
|
|
|
|
|
for i := 0; i < len(content); i++ {
|
2023-10-18 01:11:53 +00:00
|
|
|
if content[i].Kind == SequenceNode {
|
2021-10-26 04:42:25 +00:00
|
|
|
flatten(content[i], depth-1)
|
|
|
|
for j := 0; j < len(content[i].Content); j++ {
|
|
|
|
newSeq = append(newSeq, content[i].Content[j])
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
newSeq = append(newSeq, content[i])
|
|
|
|
}
|
|
|
|
}
|
2023-10-18 01:11:53 +00:00
|
|
|
node.Content = make([]*CandidateNode, 0)
|
|
|
|
node.AddChildren(newSeq)
|
2021-10-26 04:42:25 +00:00
|
|
|
}
|
|
|
|
|
2024-01-11 02:17:34 +00:00
|
|
|
func flattenOp(_ *dataTreeNavigator, context Context, expressionNode *ExpressionNode) (Context, error) {
|
2021-10-26 04:42:25 +00:00
|
|
|
|
|
|
|
log.Debugf("-- flatten Operator")
|
|
|
|
depth := expressionNode.Operation.Preferences.(flattenPreferences).depth
|
|
|
|
|
|
|
|
for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
|
|
|
|
candidate := el.Value.(*CandidateNode)
|
2023-10-18 01:11:53 +00:00
|
|
|
if candidate.Kind != SequenceNode {
|
|
|
|
return Context{}, fmt.Errorf("only arrays are supported for flatten")
|
2021-10-26 04:42:25 +00:00
|
|
|
}
|
|
|
|
|
2023-10-18 01:11:53 +00:00
|
|
|
flatten(candidate, depth)
|
2021-10-26 04:42:25 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
return context, nil
|
|
|
|
|
|
|
|
}
|