From d0688ff2306e6e2dab636d9fa667d90315697155 Mon Sep 17 00:00:00 2001 From: Yin Da Date: Fri, 26 May 2023 11:24:20 +0800 Subject: [PATCH 1/2] Feat: split FieldValues function for cue Signed-off-by: Yin Da --- cue/util/iterate.go | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/cue/util/iterate.go b/cue/util/iterate.go index 534c019..8ad2356 100644 --- a/cue/util/iterate.go +++ b/cue/util/iterate.go @@ -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() @@ -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 } From 721c5df36c10d97f4d3a6b2eab6645d74e3f13bd Mon Sep 17 00:00:00 2001 From: Yin Da Date: Fri, 26 May 2023 13:55:08 +0800 Subject: [PATCH 2/2] add maps.From Signed-off-by: Yin Da --- util/maps/utils.go | 10 ++++++++++ util/maps/utils_test.go | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/util/maps/utils.go b/util/maps/utils.go index d967145..9a6c079 100644 --- a/util/maps/utils.go +++ b/util/maps/utils.go @@ -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 +} diff --git a/util/maps/utils_test.go b/util/maps/utils_test.go index 2ab4209..4080e8e 100644 --- a/util/maps/utils_test.go +++ b/util/maps/utils_test.go @@ -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) + })) }