yq/pkg/yqlib/operator_shuffle.go

35 lines
886 B
Go
Raw Normal View History

2023-02-10 18:08:20 +00:00
package yqlib
import (
"container/list"
"fmt"
"math/rand"
)
2024-01-11 02:17:34 +00:00
func shuffleOperator(_ *dataTreeNavigator, context Context, _ *ExpressionNode) (Context, error) {
2023-02-10 18:08:20 +00:00
// ignore CWE-338 gosec issue of not using crypto/rand
// this is just to shuffle an array rather generating a
// secret or something that needs proper rand.
myRand := rand.New(rand.NewSource(Now().UnixNano())) // #nosec
results := list.New()
for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
candidate := el.Value.(*CandidateNode)
if candidate.Kind != SequenceNode {
return context, fmt.Errorf("node at path [%v] is not an array (it's a %v)", candidate.GetNicePath(), candidate.Tag)
2023-02-10 18:08:20 +00:00
}
result := candidate.Copy()
2023-02-10 18:08:20 +00:00
a := result.Content
myRand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] })
results.PushBack(result)
2023-02-10 18:08:20 +00:00
}
return context.ChildContext(results), nil
}