1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-07 06:02:27 +08:00

Compare commits

..

5 Commits

Author SHA1 Message Date
dudaodong
26b59dd56b update: update go test command in workflows/codecov.yml 2021-12-14 11:02:19 +08:00
dudaodong
143aba7112 release: update readme file, new feature for functional programming 2021-12-14 10:55:07 +08:00
dudaodong
60f3a72c88 refactor: update Compose func in function.go 2021-12-14 10:29:53 +08:00
dudaodong
d1b74cfcfb feat: add Compose in function.go 2021-12-13 20:15:34 +08:00
dudaodong
72a89be8c1 feat: add function package for funcational programming 2021-12-11 13:30:11 +08:00
6 changed files with 301 additions and 13 deletions

View File

@@ -17,6 +17,6 @@ jobs:
with:
go-version: "1.16"
- name: Run coverage
run: go test -v ./... -race -coverprofile=coverage.txt -covermode=atomic
run: go test -v ./... -coverprofile=coverage.txt -covermode=atomic
- name: Upload coverage to Codecov
run: bash <(curl -s https://codecov.io/bash)

View File

@@ -6,7 +6,7 @@
<div align="center" style="text-align: center;">
![Go version](https://img.shields.io/badge/go-%3E%3D1.16<recommend>-9cf)
[![Release](https://img.shields.io/badge/release-1.0.6-green.svg)](https://github.com/duke-git/lancet/releases)
[![Release](https://img.shields.io/badge/release-1.0.7-green.svg)](https://github.com/duke-git/lancet/releases)
[![GoDoc](https://godoc.org/github.com//duke-git/lancet?status.svg)](https://pkg.go.dev/github.com/duke-git/lancet)
[![Go Report Card](https://goreportcard.com/badge/github.com/duke-git/lancet)](https://goreportcard.com/report/github.com/duke-git/lancet)
[![codecov](https://codecov.io/gh/duke-git/lancet/branch/main/graph/badge.svg?token=FC48T1F078)](https://codecov.io/gh/duke-git/lancet)
@@ -246,7 +246,39 @@ func main() {
func Comma(v interface{}, symbol string) string //add comma to number by every 3 numbers from right. ahead by symbol char
```
#### 6. netutil is for net process
#### 6. function can control the function execution and support functional programming
- Control function execution and support functional programming.
- Usage: import "github.com/duke-git/lancet/function"
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/function"
)
func main() {
var print = func(s string) {
fmt.Println(s)
}
function.Delay(2*time.Second, print, "hello world")
}
```
- Function list:
```go
func After(n int, fn interface{}) func(args ...interface{}) []reflect.Value //creates a function that invokes func once it's called n or more times
func Before(n int, fn interface{}) func(args ...interface{}) []reflect.Value //creates a function that invokes func once it's called less than n times
func (f Fn) Curry(i interface{}) func(...interface{}) interface{} //make a curryed function
func Compose(fnList ...func(...interface{}) interface{}) func(...interface{}) interface{} //compose the functions from right to left
func Delay(delay time.Duration, fn interface{}, args ...interface{}) //invoke function after delayed time
func Schedule(d time.Duration, fn interface{}, args ...interface{}) chan bool //invoke function every duration time, util close the returned bool chan
```
#### 7. netutil is for net process
- Ip and http request method.
- Usage: import "github.com/duke-git/lancet/netutil".
@@ -293,7 +325,7 @@ func HttpPatch(url string, params ...interface{}) (*http.Response, error) //http
func ConvertMapToQueryString(param map[string]interface{}) string //convert map to url query string
```
#### 7. random is for rand string and int generation
#### 8. random is for rand string and int generation
- Generate random string and int.
- Usage: import "github.com/duke-git/lancet/random".
@@ -322,7 +354,7 @@ func RandInt(min, max int) int //generate random int
func RandString(length int) string //generate random string
```
#### 8. slice is for process slice
#### 9. slice is for process slice
- Contain function for process slice.
- Usage: import "github.com/duke-git/lancet/slice"
@@ -369,7 +401,7 @@ func Unique(slice interface{}) interface{} //remove duplicate elements in slice
func UpdateByIndex(slice interface{}, index int, value interface{}) (interface{}, error) //update the slice element at index.
```
#### 9. strutil is for processing string
#### 10. strutil is for processing string
- Contain functions to precess string
- Usage: import "github.com/duke-git/lancet/strutil"
@@ -409,7 +441,7 @@ func ReverseStr(s string) string //return string whose char order is reversed to
func SnakeCase(s string) string //covert string to snake_case "fooBar" -> "foo_bar"
```
#### 10. validator is for data validation
#### 11. validator is for data validation
- Contain function for data validation.
- Usage: import "github.com/duke-git/lancet/validator".

View File

@@ -6,7 +6,7 @@
<div align="center" style="text-align: center;">
![Go version](https://img.shields.io/badge/go-%3E%3D1.16<recommend>-9cf)
[![Release](https://img.shields.io/badge/release-1.0.6-green.svg)](https://github.com/duke-git/lancet/releases)
[![Release](https://img.shields.io/badge/release-1.0.7-green.svg)](https://github.com/duke-git/lancet/releases)
[![GoDoc](https://godoc.org/github.com//duke-git/lancet?status.svg)](https://pkg.go.dev/github.com/duke-git/lancet)
[![Go Report Card](https://goreportcard.com/badge/github.com/duke-git/lancet)](https://goreportcard.com/report/github.com/duke-git/lancet)
[![codecov](https://codecov.io/gh/duke-git/lancet/branch/main/graph/badge.svg?token=FC48T1F078)](https://codecov.io/gh/duke-git/lancet)
@@ -247,7 +247,39 @@ func main() {
func Comma(v interface{}, symbol string) string //用逗号每隔3位分割数字/字符串
```
#### 6. netutil网络处理包
#### 6. function包可以控制函数执行支持部分函数式编程
- 控制函数执行,支持部分函数式编程
- 导入包import "github.com/duke-git/lancet/function"
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/function"
)
func main() {
var print = func(s string) {
fmt.Println(s)
}
function.Delay(2*time.Second, print, "hello world")
}
```
- Function list:
```go
func After(n int, fn interface{}) func(args ...interface{}) []reflect.Value //创建一个函数, 只有在运行了n次之后才有效果
func Before(n int, fn interface{}) func(args ...interface{}) []reflect.Value //创建一个函数,调用不超过n次。 当n已经达到时最后一个函数调用的结果将被记住并返回
func (f Fn) Curry(i interface{}) func(...interface{}) interface{} //函数柯里化
func Compose(fnList ...func(...interface{}) interface{}) func(...interface{}) interface{} //从右至左组合函数
func Delay(delay time.Duration, fn interface{}, args ...interface{}) //延迟调用函数
func Schedule(d time.Duration, fn interface{}, args ...interface{}) chan bool //每隔duration时间调用函数, 关闭返回通道可以停止调用
```
#### 7. netutil网络处理包
- 处理ip, http请求相关函数
- 导入包import "github.com/duke-git/lancet/netutil"
@@ -294,7 +326,7 @@ func HttpPatch(url string, params ...interface{}) (*http.Response, error) //http
func ConvertMapToQueryString(param map[string]interface{}) string //将map转换成url query string
```
#### 7. random随机数处理包
#### 8. random随机数处理包
- 生成和处理随机数
- 导入包import "github.com/duke-git/lancet/random"
@@ -323,7 +355,7 @@ func RandInt(min, max int) int //生成随机int
func RandString(length int) string //生成随机string
```
#### 8. slice切片操作包
#### 9. slice切片操作包
- 切片操作相关函数
- 导入包import "github.com/duke-git/lancet/slice"
@@ -370,7 +402,7 @@ func Unique(slice interface{}) interface{} //去重切片
func UpdateByIndex(slice interface{}, index int, value interface{}) (interface{}, error) //在切片中index位置更新value
```
#### 9. strutil字符串处理包
#### 10. strutil字符串处理包
- 字符串操作相关函数
- 导入包import "github.com/duke-git/lancet/strutil"
@@ -410,7 +442,7 @@ func ReverseStr(s string) string //字符串逆袭
func SnakeCase(s string) string //字符串转为SnakeCase, "fooBar" -> "foo_bar"
```
#### 10. validator验证器包
#### 11. validator验证器包
- 数据校验相关函数
- 导入包import "github.com/duke-git/lancet/validator"

87
function/function.go Normal file
View File

@@ -0,0 +1,87 @@
// Copyright 2021 dudaodong@gmail.com. All rights reserved.
// Use of this source code is governed by MIT license
// Package function implements some functions for control the function execution and some is for functional programming.
package function
import (
"reflect"
"time"
)
// After creates a function that invokes func once it's called n or more times
func After(n int, fn interface{}) func(args ...interface{}) []reflect.Value {
return func(args ...interface{}) []reflect.Value {
n--
if n < 1 {
return invokeFunc(fn, args...)
}
return nil
}
}
// Before creates a function that invokes func once it's called less than n times
func Before(n int, fn interface{}) func(args ...interface{}) []reflect.Value {
var res []reflect.Value
return func(args ...interface{}) []reflect.Value {
if n > 0 {
res = invokeFunc(fn, args...)
}
if n <= 0 {
fn = nil
}
n--
return res
}
}
type Fn func(...interface{}) interface{}
// Curry make a curryed function
func (f Fn) Curry(i interface{}) func(...interface{}) interface{} {
return func(values ...interface{}) interface{} {
v := append([]interface{}{i}, values...)
return f(v...)
}
}
// Compose compose the functions from right to left
func Compose(fnList ...func(...interface{}) interface{}) func(...interface{}) interface{} {
return func(s... interface{}) interface{} {
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...)
}
// Schedule invoke function every duration time, util close the returned bool chan
func Schedule(d time.Duration, fn interface{}, args ...interface{}) chan bool {
quit := make(chan bool)
go func() {
for {
invokeFunc(fn, args...)
select {
case <-time.After(d):
case <-quit:
return
}
}
}()
return quit
}

114
function/function_test.go Normal file
View File

@@ -0,0 +1,114 @@
package function
import (
"fmt"
"reflect"
"strings"
"testing"
"time"
)
func TestAfter(t *testing.T) {
arr := []string{"a", "b"}
f := After(len(arr), func(i int) int {
fmt.Println("print done")
return i
})
type cb func(args ...interface{}) []reflect.Value
print := func(i int, s string, fn cb) {
fmt.Printf("print: arr[%d] is %s \n", i, s)
v := fn(i)
if v != nil {
vv := v[0].Int()
if vv != 1 {
t.FailNow()
}
}
}
fmt.Println("print: arr is", arr)
for i := 0; i < len(arr); i++ {
print(i, arr[i], f)
}
}
func TestBefore(t *testing.T) {
arr := []string{"a", "b", "c", "d", "e"}
f := Before(3, func(i int) int {
return i
})
var res []int64
type cb func(args ...interface{}) []reflect.Value
appendStr := func(i int, s string, fn cb) {
fmt.Printf("appendStr: arr[%d] is %s \n", i, s)
v := fn(i)
res = append(res, v[0].Int())
}
for i := 0; i < len(arr); i++ {
appendStr(i, arr[i], f)
}
expect := []int64{0, 1, 2, 2, 2}
if !reflect.DeepEqual(expect, res) {
t.FailNow()
}
}
func TestCurry(t *testing.T) {
add := func(a, b int) int {
return a + b
}
var addCurry Fn = func(values ...interface{}) interface{} {
return add(values[0].(int), values[1].(int))
}
add1 := addCurry.Curry(1)
v := add1(2)
if v != 3 {
t.FailNow()
}
}
func TestCompose(t *testing.T) {
toUpper := func(a ...interface{}) interface{} {
return strings.ToUpper(a[0].(string))
}
toLower := func(a ...interface{}) interface{} {
return strings.ToLower(a[0].(string))
}
expect := toUpper(toLower("aBCde"))
cf := Compose(toUpper, toLower)
res := cf("aBCde")
if res != expect {
t.FailNow()
}
}
func TestDelay(t *testing.T) {
var print = func(s string) {
fmt.Println(s)
}
Delay(2*time.Second, print, "test delay")
}
func TestSchedule(t *testing.T) {
var res []string
appendStr := func(s string) {
fmt.Println(s)
res = append(res, s)
}
stop := Schedule(1*time.Second, appendStr, "*")
time.Sleep(5 * time.Second)
close(stop)
expect := []string{"*", "*", "*", "*", "*"}
if !reflect.DeepEqual(expect, res) {
t.FailNow()
}
fmt.Println("done")
}

23
function/function_util.go Normal file
View File

@@ -0,0 +1,23 @@
package function
import (
"fmt"
"reflect"
)
func invokeFunc(fn interface{}, args ...interface{}) []reflect.Value {
fv := functionValue(fn)
params := make([]reflect.Value, len(args))
for i, item := range args {
params[i] = reflect.ValueOf(item)
}
return fv.Call(params)
}
func functionValue(function interface{}) reflect.Value {
v := reflect.ValueOf(function)
if v.Kind() != reflect.Func {
panic(fmt.Sprintf("Invalid function type, value of type %T", function))
}
return v
}