Skip to content

Commit

Permalink
✨ feat: add PipeCallback and test case
Browse files Browse the repository at this point in the history
  • Loading branch information
jingyuexing committed Nov 17, 2023
1 parent 93b1aa3 commit add1d6a
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 4 deletions.
40 changes: 40 additions & 0 deletions utils/func.go
Original file line number Diff line number Diff line change
@@ -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
}
}
30 changes: 30 additions & 0 deletions utils/func_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package utils_test

import (
"fmt"
"testing"

utils "jingyuexing.com/utils"

Check failure on line 7 in utils/func_test.go

View workflow job for this annotation

GitHub Actions / build (1.2)

cannot find package "jingyuexing.com/utils" in any of:
)

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)
}
}
3 changes: 0 additions & 3 deletions utils/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
})
Expand Down

0 comments on commit add1d6a

Please sign in to comment.