underscore icon indicating copy to clipboard operation
underscore copied to clipboard

[FEATURE] Each with multiple args

Open raphaelauv opened this issue 3 years ago • 2 comments

would you accept tests helpers on this repo ?

like parametrize ?

func parametrize[V any, T any](fn T, allValues [][]V) {
    v := reflect.ValueOf(fn)
    for _, a := range allValues {
        vargs := make([]reflect.Value, len(a))

        for i, b := range a {
            vargs[i] = reflect.ValueOf(b)
        }
        v.Call(vargs)
    }
}

func tutu(a int) int {
    return a + 1
}

func Test_tutu(t *testing.T) {
    testsArgs := [][]any{
        {t, 1, 2}, {t, 3, 4},
    }
    test := func(t *testing.T, input int, expected int) {
        assert.Equal(t, tutu(input), expected)
    }
    parametrize(test, testsArgs)
}

raphaelauv avatar Jul 05 '22 09:07 raphaelauv

Hi.

Yes, it looks like a good idea. Feel free to prepare a pull request

rjNemo avatar Jul 06 '22 11:07 rjNemo

parametrize is just a specific Each

that accepts a list of multiple parameters instead of a list of single parameter

so it could be

func EachMultiple[T any, V any](allValues [][]T, action V) {
	v := reflect.ValueOf(action)
	for _, a := range allValues {
		vargs := make([]reflect.Value, len(a))

		for i, b := range a {
			vargs[i] = reflect.ValueOf(b)
		}
		v.Call(vargs)
	}
}

I have no idea for a good name

But maybe the best would be to introduce a partial struct like in python

from functools import partial

def f(a, b, c, x):
  return 1000*a + 100*b + 10*c + x


g = partial(f, 3, 1, 4)

print(g(5))  # give 3145

raphaelauv avatar Jul 06 '22 12:07 raphaelauv