From b8563ed6467fa8070fc0153a335ae7eec2153fb0 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Sat, 15 Oct 2022 12:29:47 +0800 Subject: [PATCH] feat: add Pipeline function --- function/function.go | 12 ++++++++++++ function/function_test.go | 18 ++++++++++++++++++ function/watcher_test.go | 2 ++ 3 files changed, 32 insertions(+) diff --git a/function/function.go b/function/function.go index 67976c0..c6356c8 100644 --- a/function/function.go +++ b/function/function.go @@ -113,3 +113,15 @@ func Schedule(d time.Duration, fn any, args ...any) chan bool { return quit } + +// Pipeline takes a list of functions and returns a function whose param will be passed into +// the functions one by one. +func Pipeline[T any](funcs ...func(T) T) func(T) T { + return func(arg T) (result T) { + result = arg + for _, fn := range funcs { + result = fn(result) + } + return + } +} diff --git a/function/function_test.go b/function/function_test.go index 7f12599..1f5b7e1 100644 --- a/function/function_test.go +++ b/function/function_test.go @@ -134,3 +134,21 @@ func TestSchedule(t *testing.T) { // expected := []string{"*", "*", "*", "*", "*"} // assert.Equal(expected, res) } + +func TestPipeline(t *testing.T) { + assert := internal.NewAssert(t, "TestPipeline") + + addOne := func(x int) int { + return x + 1 + } + double := func(x int) int { + return 2 * x + } + square := func(x int) int { + return x * x + } + + f := Pipeline(addOne, double, square) + + assert.Equal(36, f(2)) +} diff --git a/function/watcher_test.go b/function/watcher_test.go index a0ab1d8..fb7c981 100644 --- a/function/watcher_test.go +++ b/function/watcher_test.go @@ -1,6 +1,7 @@ package function import ( + "fmt" "testing" "github.com/duke-git/lancet/v2/internal" @@ -34,4 +35,5 @@ func longRunningTask() { for i := 0; i < 10000000; i++ { slice = append(slice, int64(i)) } + fmt.Println(slice) }