Skip to content

Commit

Permalink
✨ feat: add ForEach
Browse files Browse the repository at this point in the history
🧹 chore: improve AccessNested function
  • Loading branch information
jingyuexing committed Jan 1, 2024
1 parent 8ffdb55 commit 79c9863
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 7 deletions.
6 changes: 6 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,9 @@ func GroupBy[T any, K comparable](slice []T, getKey func(T) K) map[K][]T {

return groups
}

func ForEach[T any](slice []T,callback func(value T,key int)){
for k, v := range slice {
callback(v,k)
}
}
39 changes: 32 additions & 7 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,43 @@ func pathParse(target string) []string {
return obj
}

func AccessNested(data map[string]interface{}, path string, delimiter string) interface{} {
func AccessNested(data any, path string, delimiter string) any {
keys := strings.Split(path, delimiter)
value := data
value := reflect.ValueOf(data)

if value.Kind() == reflect.Pointer {
value = reflect.Indirect(value)
}

for _, key := range keys {
if val, ok := value[key]; ok {
value = val.(map[string]interface{})
} else {
if !value.IsValid() {
return nil
}

switch value.Kind() {
case reflect.Pointer:
value = reflect.Indirect(value)
case reflect.Map:
mapValue := value.MapIndex(reflect.ValueOf(key))
if !mapValue.IsValid() {
return nil
}
value = mapValue
case reflect.Struct:
field := value.FieldByName(key)
if !field.IsValid() {
return nil
}
value = field
default:
return nil
}
}
return value

if value.IsValid() && value.CanInterface() {
return value.Interface()
}
return nil
}

func GetPathValue(raw string, realPath string) map[string]string {
Expand Down Expand Up @@ -170,7 +196,6 @@ func Map2Struct(source map[string]any, bindingTarget any) {
}
}


func TimeDuration(duration string) (time.Time, error) {
const (
SECOND uint64 = 1
Expand Down
17 changes: 17 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,20 @@ func TestEmit(t *testing.T){
}

}

func TestAccessNested(t *testing.T) {
type S struct {
A struct {
B int
}
}
k := &S{
A: struct{B int}{
B:33,
},
}
value := utils.AccessNested(k,"A.B",".")
if value.(int) != 33 {
t.Error("not pass")
}
}

0 comments on commit 79c9863

Please sign in to comment.