Skip to content

Commit

Permalink
Feat: split FieldValues function for cue (#86)
Browse files Browse the repository at this point in the history
* Feat: split FieldValues function for cue

Signed-off-by: Yin Da <yd219913@alibaba-inc.com>

* add maps.From

Signed-off-by: Yin Da <yd219913@alibaba-inc.com>

---------

Signed-off-by: Yin Da <yd219913@alibaba-inc.com>
  • Loading branch information
Somefive committed Jun 9, 2023
1 parent 7d5e124 commit f426bc4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
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)
}))
}

0 comments on commit f426bc4

Please sign in to comment.