Skip to content

Commit

Permalink
Merge pull request #78 from Teamwork/valuesfunc
Browse files Browse the repository at this point in the history
Adds values func
  • Loading branch information
ready4god2513 authored Feb 9, 2024
2 parents 519412a + 90a1f2b commit ea51bfb
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
10 changes: 10 additions & 0 deletions sliceutil/sliceutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,13 @@ func InterfaceSliceTo(src []interface{}, dst interface{}) interface{} {

return dstV.Interface()
}

// Values returns a list of items extracted from T, see test file for example
func Values[T comparable, N any](tt []T, fn func(T) N) []N {
ret := make([]N, len(tt))
for i, t := range tt {
ret[i] = fn(t)
}

return ret
}
41 changes: 41 additions & 0 deletions sliceutil/sliceutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -621,3 +621,44 @@ func TestInterfaceSliceTo(t *testing.T) {
}
}
}

func TestValues(t *testing.T) {
type testStruct struct {
Name string
Age int
}

cases := []struct {
in []testStruct
expected []string
}{
{
[]testStruct{
{Name: "a", Age: 1},
{Name: "b", Age: 2},
{Name: "c", Age: 3},
},
[]string{"a", "b", "c"},
},
{
[]testStruct{
{Name: "a", Age: 1},
{Name: "b", Age: 2},
{Name: "c", Age: 3},
{Name: "d", Age: 4},
},
[]string{"a", "b", "c", "d"},
},
}

for i, tc := range cases {
t.Run(fmt.Sprintf("test-%v", i), func(t *testing.T) {
got := Values(tc.in, func(t testStruct) string {
return t.Name
})
if !reflect.DeepEqual(got, tc.expected) {
t.Errorf(diff.Cmp(tc.expected, got))
}
})
}
}

0 comments on commit ea51bfb

Please sign in to comment.