1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add ForEach func

This commit is contained in:
dudaodong
2022-01-05 20:17:16 +08:00
parent 71a2ea3f20
commit df9de3065b
2 changed files with 32 additions and 0 deletions

View File

@@ -265,6 +265,22 @@ func flattenRecursive(value reflect.Value, result reflect.Value) reflect.Value {
return result
}
// ForEach iterates over elements of slice and invokes function for each element
// The function signature should be func(index int, value interface{}).
func ForEach(slice, function interface{}) {
sv := sliceValue(slice)
fn := functionValue(function)
elemType := sv.Type().Elem()
if checkSliceCallbackFuncSignature(fn, elemType, nil) {
panic("function param should be of type func(int, " + elemType.String() + ")" + elemType.String())
}
for i := 0; i < sv.Len(); i++ {
fn.Call([]reflect.Value{reflect.ValueOf(i), sv.Index(i)})
}
}
// Map creates an slice of values by running each element of `slice` thru `function`.
// The function signature should be func(index int, value interface{}) interface{}.
func Map(slice, function interface{}) interface{} {

View File

@@ -235,6 +235,22 @@ func TestFlattenDeep(t *testing.T) {
}
}
func TestForEach(t *testing.T) {
numbers := []int{1, 2, 3, 4, 5}
expected := []int{3, 4, 5, 6, 7}
var numbersAddTwo []int
ForEach(numbers, func(index int, value int) {
numbersAddTwo = append(numbersAddTwo, value+2)
})
if !reflect.DeepEqual(numbersAddTwo, expected) {
internal.LogFailedTestInfo(t, "ForEach", numbers, expected, numbersAddTwo)
t.FailNow()
}
}
func TestMap(t *testing.T) {
s1 := []int{1, 2, 3, 4}
multiplyTwo := func(i, num int) int {