diff --git a/utils/func.go b/utils/func.go new file mode 100644 index 0000000..aa0eed6 --- /dev/null +++ b/utils/func.go @@ -0,0 +1,40 @@ +package utils + +import ( + "errors" + "fmt" +) + +// PipeCallback executes a series of functions where the output of each function is passed as input to the next function. +// Returns a function that can be invoked to run the entire execution process. +func PipeCallback[T any](fns ...func(args T) T) func(args T) T { + return func(args T) T { + result := args + for _, fn := range fns { + result = fn(result) + } + return result + } +} + +func Times(cb func(...any) any, x int) func(...any) any { + value := any(nil) + times := 0 + return func(args ...any) any { + if times < x { + defer func() { + if r := recover(); r != nil { + err, ok := r.(error) + if !ok { + err = errors.New(fmt.Sprint(r)) + } + fmt.Println("Error occurred:", err) + } + }() + value = cb(args...) + times++ + } + + return value + } +} diff --git a/utils/func_test.go b/utils/func_test.go new file mode 100644 index 0000000..f6b4fc6 --- /dev/null +++ b/utils/func_test.go @@ -0,0 +1,30 @@ +package utils_test + +import ( + "fmt" + "testing" + + utils "jingyuexing.com/utils" +) + +func TestPipelCallback(t *testing.T){ + addOne := func(x int) int { + return x + 1 + } + + double := func(x int) int { + return x * 2 + } + + square := func(x int) int { + return x * x + } + composeFunc := utils.PipeCallback(addOne,double,square) + + result := composeFunc(55) + if result != 12544 { + t.Error("no pass") + }else{ + fmt.Printf("%d",result) + } +} diff --git a/utils/options.go b/utils/options.go index 3be16a0..6ba16b5 100644 --- a/utils/options.go +++ b/utils/options.go @@ -77,9 +77,6 @@ type People struct { } func main(){ - var age *int = nil; - ok := Option(age) - vals := *ok.Expect("this is nil pointer") somePeople := Option(&People{ Age: 20, Name: "Gog", diff --git a/utils/utils_test.go b/utils/utils_test.go index 831e572..4eb23b4 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -8,7 +8,7 @@ import ( ) func TestFormat(t *testing.T) { - result := utils.Template("{a} {b}", map[string]string{ + result := utils.Template("{a} {b}", map[string]any{ "a": "hello", "b": "world", })