mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-12 16:52:29 +08:00
feat: add ForEach func
This commit is contained in:
@@ -265,6 +265,22 @@ func flattenRecursive(value reflect.Value, result reflect.Value) reflect.Value {
|
|||||||
return result
|
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`.
|
// 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{}.
|
// The function signature should be func(index int, value interface{}) interface{}.
|
||||||
func Map(slice, function interface{}) interface{} {
|
func Map(slice, function interface{}) interface{} {
|
||||||
|
|||||||
@@ -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) {
|
func TestMap(t *testing.T) {
|
||||||
s1 := []int{1, 2, 3, 4}
|
s1 := []int{1, 2, 3, 4}
|
||||||
multiplyTwo := func(i, num int) int {
|
multiplyTwo := func(i, num int) int {
|
||||||
|
|||||||
Reference in New Issue
Block a user