Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: split FieldValues function for cue #86

Merged
merged 2 commits into from
Jun 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions cue/util/iterate.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,25 @@ const orderKey = "step"
// Iterate over all fields of the cue.Value with fn, if fn returns true,
// iteration stops
func Iterate(value cue.Value, fn func(v cue.Value) (stop bool)) (stop bool) {
var it *cue.Iterator
// skip definition
if strings.Contains(value.Path().String(), "#") {
return false
}
values := FieldValues(value)
for _, val := range values {
if Iterate(val, fn) {
return true
}
}
return fn(value)
}

// FieldValues the field values of the given value
// If the given value is a list, all its items will be returned
// If the given value is a map, all its key-value entries will be returned
// The returned values will be sorted in the order of their "step" attribute
func FieldValues(value cue.Value) []cue.Value {
var it *cue.Iterator
switch value.Kind() {
case cue.ListKind:
_it, _ := value.List()
Expand All @@ -59,10 +73,5 @@ func Iterate(value cue.Value, fn func(v cue.Value) (stop bool)) (stop bool) {
return x < y
}
})
for _, val := range values {
if Iterate(val, fn) {
return true
}
}
return fn(value)
return values
}
10 changes: 10 additions & 0 deletions util/maps/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,13 @@ func Copy[K comparable, V any](m map[K]V) map[K]V {
}
return _m
}

// From create a map from array
func From[T any, K comparable, V any](arr []T, fn func(T) (K, V)) map[K]V {
_m := make(map[K]V, len(arr))
for _, item := range arr {
k, v := fn(item)
_m[k] = v
}
return _m
}
4 changes: 4 additions & 0 deletions util/maps/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,8 @@ func TestUtils(t *testing.T) {
_m = maps.Filter(m, func(k string, _ int) bool { return k == "a" })
_m = maps.Map(_m, func(v int) int { return v + 1 })
require.Equal(t, map[string]int{"a": 2}, _m)

require.Equal(t, map[int]string{1: "0", 2: "1"}, maps.From([]int{0, 1}, func(i int) (int, string) {
return i + 1, fmt.Sprintf("%d", i)
}))
}