Skip to content

Commit

Permalink
feat: add Compose in function.go
Browse files Browse the repository at this point in the history
  • Loading branch information
duke-git committed Dec 13, 2021
1 parent 72a89be commit d1b74cf
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
19 changes: 17 additions & 2 deletions function/function.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2021 [email protected]. All rights reserved.
// Use of this source code is governed by MIT license

// Package function implements some functions for functional programming.
// Package function implements some functions for control the function execution and some is for functional programming.

package function

Expand Down Expand Up @@ -47,7 +47,22 @@ func (f Fn) Curry(i interface{}) func(...interface{}) interface{} {
}
}

// Delay make the function excution after delayed time
// Compose compose the functions from right to left
func Compose(fnList ...func(...string) string) func(...string) string {
return func(s... string) string {
f := fnList[0]
restFn := fnList[1:]

if len(fnList) == 1 {
return f(s...)
}

return f(Compose(restFn...)(s...))
}
}


// Delay make the function execution after delayed time
func Delay(delay time.Duration, fn interface{}, args ...interface{}) {
time.Sleep(delay)
invokeFunc(fn, args...)
Expand Down
21 changes: 21 additions & 0 deletions function/function_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package function
import (
"fmt"
"reflect"
"strings"
"testing"
"time"
)
Expand Down Expand Up @@ -69,6 +70,26 @@ func TestCurry(t *testing.T) {
}
}

func TestCompose(t *testing.T) {
toUpper := func(a... string) string {
return strings.ToUpper(a[0])
}

toLower := func(a... string) string {
return strings.ToLower(a[0])
}

expect := toUpper(toLower("aBCde"))
cf := Compose(toUpper, toLower)
res := cf("aBCde")

fmt.Println(res, expect)
if res != expect {
t.FailNow()
}

}

func TestDelay(t *testing.T) {
var print = func(s string) {
fmt.Println(s)
Expand Down

0 comments on commit d1b74cf

Please sign in to comment.