1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-05 05:12:26 +08:00

Compare commits

...

23 Commits

Author SHA1 Message Date
dudaodong
051f20caef release: v1.1.4, merge pr7 and pr8 2021-12-30 20:25:20 +08:00
donutloop
613785b07c function: catch earlier programming error (#8)
Place at first line of the function body a function type safe guard
check.
2021-12-30 20:22:00 +08:00
donutloop
0b0eb695e8 datetime: optimized func calls (#7)
Replace time parsing calls with less expensive operations
2021-12-30 10:29:10 +08:00
dudaodong
745082fff1 fix: update api url for http timeout issue in the task of github actions 2021-12-29 11:39:48 +08:00
dudaodong
24b8da360e release: v1.1.3, merge pr5 and pr6 2021-12-29 09:55:42 +08:00
donutloop
b106c428ae Every: use int counter (#6)
Use counter to verify all elements passed the perdicate func.
Replace slice of indexes with int counter.
2021-12-29 09:51:50 +08:00
dudaodong
8b1171d0cb fmt: go fmt for request_test.go 2021-12-28 19:28:55 +08:00
donutloop
ab012f2545 LowerFirst: use slicing and utf8 func tools (#5)
Replace looping with slicing and utf8 func tools operations.
2021-12-28 19:25:44 +08:00
dudaodong
a952cb208a release v1.1.2 2021-12-28 11:28:00 +08:00
dudaodong
f239a8ca8e fix: fix request timeout issue 2021-12-28 11:04:57 +08:00
dudaodong
5c6626b37e fmt: go fmt for function.go 2021-12-28 11:00:43 +08:00
dudaodong
16b5101600 fix: fix TestHttpPost timeout issue 2021-12-28 10:56:54 +08:00
dudaodong
ec983b7aa6 fix: fix
Intersection slice issue
2021-12-28 10:16:53 +08:00
dudaodong
56fc2aabd6 fmt: fix lint issue 2021-12-28 10:08:08 +08:00
dudaodong
0ddd52225b Merge branch 'main' of github.com:duke-git/lancet into main 2021-12-28 10:07:33 +08:00
donutloop
3919160e38 Optimized: Capitalize (#4)
* Use unicode.ToUpper func to convert first letter in string to upper case
letter.

* Preallocate memory with correct length and cap because the final
  string is not changing.
2021-12-28 10:04:15 +08:00
dudaodong
40ec5bc0f6 fmt: fix lint issue 2021-12-27 20:40:54 +08:00
dudaodong
99faeccb05 feat: add Intersection, Union, Without func for slice/slice.go 2021-12-27 19:54:04 +08:00
dudaodong
ad777bc877 feat: add Intersection, Union, Without func for slice/slice.go 2021-12-27 19:47:45 +08:00
dudaodong
589ce7404f refactor: update painc message 2021-12-27 15:12:18 +08:00
dudaodong
6ab4fca433 fmt: go fmt fileutil/file_test.go and function/function.go 2021-12-26 21:41:46 +08:00
dudaodong
b33a9cbfe3 release v1.0.10 2021-12-26 21:20:18 +08:00
donutloop
9ad9d1805b Regex validators: Precompile all known regex patterns (#3)
Reduce executions time of pattern matching, regex patterns are expensive to
compile at runtime.
2021-12-26 21:16:20 +08:00
13 changed files with 320 additions and 139 deletions

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.9-green.svg)](https://github.com/duke-git/lancet/releases)
[![Release](https://img.shields.io/badge/release-1.1.4-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)
@@ -391,6 +391,7 @@ func Filter(slice, function interface{}) interface{} //filter slice, function si
func Find(slice, function interface{}) interface{} //iterates over elements of slice, returning the first one that passes a truth test on function.function signature should be func(index int, value interface{}) bool .
func IntSlice(slice interface{}) ([]int, error) //convert value to int slice
func InterfaceSlice(slice interface{}) []interface{} //convert value to interface{} slice
func Intersection(slices ...interface{}) interface{} //creates a slice of unique values that included by all slices.
func InsertByIndex(slice interface{}, index int, value interface{}) (interface{}, error) //insert the element into slice at index.
func Map(slice, function interface{}) interface{} //map lisce, function signature should be func(index int, value interface{}) interface{}
func ReverseSlice(slice interface{}) //revere slice
@@ -399,7 +400,9 @@ func SortByField(slice interface{}, field string, sortType ...string) error //so
func Some(slice, function interface{}) bool //return true if any of the values in the list pass the predicate function, function signature should be func(index int, value interface{}) bool
func StringSlice(slice interface{}) []string //convert value to string slice
func Unique(slice interface{}) interface{} //remove duplicate elements in slice
func Union(slices ...interface{}) interface{} //Union creates a slice of unique values, in order, from all given slices. using == for equality comparisons.
func UpdateByIndex(slice interface{}, index int, value interface{}) (interface{}, error) //update the slice element at index.
func Without(slice interface{}, values ...interface{}) interface{} //creates a slice excluding all given values
```
#### 10. strutil is for processing string

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.9-green.svg)](https://github.com/duke-git/lancet/releases)
[![Release](https://img.shields.io/badge/release-1.1.4-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)
@@ -392,6 +392,7 @@ func Find(slice, function interface{}) interface{} //查找slice中第一个符
func Filter(slice, function interface{}) interface{} //过滤slice, 函数签名func(index int, value interface{}) bool
func IntSlice(slice interface{}) ([]int, error) //转成int切片
func InterfaceSlice(slice interface{}) []interface{} //转成interface{}切片
func Intersection(slices ...interface{}) interface{} //slice交集去重
func InsertByIndex(slice interface{}, index int, value interface{}) (interface{}, error) //在切片中index位置插入value
func Map(slice, function interface{}) interface{} //遍历切片, 函数签名func(index int, value interface{}) interface{}
func ReverseSlice(slice interface{}) //反转切片
@@ -400,7 +401,9 @@ func Some(slice, function interface{}) bool //slice中任意一个元素都符
func SortByField(slice interface{}, field string, sortType ...string) error //对struct切片进行排序
func StringSlice(slice interface{}) []string //转为string切片
func Unique(slice interface{}) interface{} //去重切片
func Union(slices ...interface{}) interface{} //slice并集, 去重
func UpdateByIndex(slice interface{}, index int, value interface{}) (interface{}, error) //在切片中index位置更新value
func Without(slice interface{}, values ...interface{}) interface{} //slice去除values
```
#### 10. strutil字符串处理包

View File

@@ -25,7 +25,7 @@
package datetime
import (
"strconv"
"fmt"
"time"
)
@@ -56,24 +56,17 @@ func init() {
// AddMinute add or sub minute to the time
func AddMinute(t time.Time, minute int64) time.Time {
s := strconv.FormatInt(minute, 10)
m, _ := time.ParseDuration(s + "m")
return t.Add(m)
return t.Add(time.Minute * time.Duration(minute))
}
// AddHour add or sub hour to the time
func AddHour(t time.Time, hour int64) time.Time {
s := strconv.FormatInt(hour, 10)
h, _ := time.ParseDuration(s + "h")
return t.Add(h)
return t.Add(time.Hour * time.Duration(hour))
}
// AddDay add or sub day to the time
func AddDay(t time.Time, day int64) time.Time {
dayHours := day * 24
d := strconv.FormatInt(dayHours, 10)
h, _ := time.ParseDuration(d + "h")
return t.Add(h)
return t.Add(24 * time.Hour * time.Duration(day))
}
// GetNowDate return format yyyy-mm-dd of current date
@@ -109,7 +102,11 @@ func FormatTimeToStr(t time.Time, format string) string {
}
// FormatStrToTime convert string to time
func FormatStrToTime(str, format string) time.Time {
t, _ := time.Parse(timeFormat[format], str)
return t
func FormatStrToTime(str, format string) (time.Time, error) {
v, ok := timeFormat[format]
if !ok {
return time.Time{}, fmt.Errorf("format %s not found", format)
}
return time.Parse(v, str)
}

View File

@@ -135,7 +135,10 @@ func TestFormatStrToTime(t *testing.T) {
"2021/01"}
for i := 0; i < len(cases); i++ {
res := FormatStrToTime(datetimeStr[i], cases[i])
res, err := FormatStrToTime(datetimeStr[i], cases[i])
if err != nil {
t.Fatal(err)
}
expected, _ := time.Parse(formats[i], datetimeStr[i])
if res != expected {
utils.LogFailedTestInfo(t, "FormatTimeToStr", cases[i], expected, res)

View File

@@ -135,4 +135,4 @@ func TestReadFileByLine(t *testing.T) {
if !reflect.DeepEqual(res, expected) {
utils.LogFailedTestInfo(t, "ReadFileByLine", path, expected, res)
}
}
}

View File

@@ -2,7 +2,6 @@
// 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 (
@@ -12,10 +11,12 @@ import (
// 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 {
// Catch programming error while constructing the closure
MustBeFunction(fn)
return func(args ...interface{}) []reflect.Value {
n--
if n < 1 {
return invokeFunc(fn, args...)
return unsafeInvokeFunc(fn, args...)
}
return nil
}
@@ -23,11 +24,12 @@ func After(n int, fn interface{}) func(args ...interface{}) []reflect.Value {
// 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 {
// Catch programming error while constructing the closure
MustBeFunction(fn)
var res []reflect.Value
return func(args ...interface{}) []reflect.Value {
if n > 0 {
res = invokeFunc(fn, args...)
res = unsafeInvokeFunc(fn, args...)
}
if n <= 0 {
fn = nil
@@ -37,9 +39,10 @@ func Before(n int, fn interface{}) func(args ...interface{}) []reflect.Value {
}
}
// Fn is for curry function which is func(...interface{}) interface{}
type Fn func(...interface{}) interface{}
// Curry make a curryed function
// Curry make a curry function
func (f Fn) Curry(i interface{}) func(...interface{}) interface{} {
return func(values ...interface{}) interface{} {
v := append([]interface{}{i}, values...)
@@ -49,7 +52,7 @@ func (f Fn) Curry(i interface{}) func(...interface{}) interface{} {
// Compose compose the functions from right to left
func Compose(fnList ...func(...interface{}) interface{}) func(...interface{}) interface{} {
return func(s... interface{}) interface{} {
return func(s ...interface{}) interface{} {
f := fnList[0]
restFn := fnList[1:]
@@ -61,7 +64,6 @@ func Compose(fnList ...func(...interface{}) interface{}) func(...interface{}) in
}
}
// Delay make the function execution after delayed time
func Delay(delay time.Duration, fn interface{}, args ...interface{}) {
time.Sleep(delay)
@@ -70,11 +72,12 @@ func Delay(delay time.Duration, fn interface{}, args ...interface{}) {
// Schedule invoke function every duration time, util close the returned bool chan
func Schedule(d time.Duration, fn interface{}, args ...interface{}) chan bool {
// Catch programming error while constructing the closure
MustBeFunction(fn)
quit := make(chan bool)
go func() {
for {
invokeFunc(fn, args...)
unsafeInvokeFunc(fn, args...)
select {
case <-time.After(d):
case <-quit:

View File

@@ -14,6 +14,15 @@ func invokeFunc(fn interface{}, args ...interface{}) []reflect.Value {
return fv.Call(params)
}
func unsafeInvokeFunc(fn interface{}, args ...interface{}) []reflect.Value {
fv := reflect.ValueOf(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 {
@@ -21,3 +30,10 @@ func functionValue(function interface{}) reflect.Value {
}
return v
}
func MustBeFunction(function interface{}) {
v := reflect.ValueOf(function)
if v.Kind() != reflect.Func {
panic(fmt.Sprintf("Invalid function type, value of type %T", function))
}
}

View File

@@ -11,16 +11,12 @@ import (
)
func TestHttpGet(t *testing.T) {
_, e := HttpGet("", nil)
if e == nil {
t.FailNow()
url := "https://jsonplaceholder.typicode.com/todos/1"
header := map[string]string{
"Content-Type": "application/json",
}
url := "https://gutendex.com/books?"
queryParams := make(map[string]interface{})
queryParams["ids"] = "1"
resp, err := HttpGet(url, nil, queryParams)
resp, err := HttpGet(url, header)
if err != nil {
log.Fatal(err)
t.FailNow()
@@ -28,23 +24,20 @@ func TestHttpGet(t *testing.T) {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response: ", resp.StatusCode, string(body))
}
func TestHttpPost(t *testing.T) {
url := "http://public-api-v1.aspirantzhang.com/users"
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
user := User{
"test",
"test@test.com",
}
bodyParams, _ := json.Marshal(user)
url := "https://jsonplaceholder.typicode.com/todos"
header := map[string]string{
"Content-Type": "application/json",
}
type Todo struct {
UserId int `json:"userId"`
Title string `json:"title"`
}
todo := Todo{1, "TestAddToDo"}
bodyParams, _ := json.Marshal(todo)
resp, err := HttpPost(url, header, nil, bodyParams)
if err != nil {
log.Fatal(err)
@@ -55,19 +48,18 @@ func TestHttpPost(t *testing.T) {
}
func TestHttpPut(t *testing.T) {
url := "http://public-api-v1.aspirantzhang.com/users/10420"
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
user := User{
"test",
"test@test.com",
}
bodyParams, _ := json.Marshal(user)
url := "https://jsonplaceholder.typicode.com/todos/1"
header := map[string]string{
"Content-Type": "application/json",
}
type Todo struct {
Id int `json:"id"`
UserId int `json:"userId"`
Title string `json:"title"`
}
todo := Todo{1, 1, "TestPutToDo"}
bodyParams, _ := json.Marshal(todo)
resp, err := HttpPut(url, header, nil, bodyParams)
if err != nil {
log.Fatal(err)
@@ -77,8 +69,30 @@ func TestHttpPut(t *testing.T) {
fmt.Println("response: ", resp.StatusCode, string(body))
}
func TestHttpPatch(t *testing.T) {
url := "https://jsonplaceholder.typicode.com/todos/1"
header := map[string]string{
"Content-Type": "application/json",
}
type Todo struct {
Id int `json:"id"`
UserId int `json:"userId"`
Title string `json:"title"`
}
todo := Todo{1, 1, "TestPatchToDo"}
bodyParams, _ := json.Marshal(todo)
resp, err := HttpPatch(url, header, nil, bodyParams)
if err != nil {
log.Fatal(err)
t.FailNow()
}
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response: ", resp.StatusCode, string(body))
}
func TestHttpDelete(t *testing.T) {
url := "http://public-api-v1.aspirantzhang.com/users/10420"
url := "https://jsonplaceholder.typicode.com/todos/1"
resp, err := HttpDelete(url)
if err != nil {
log.Fatal(err)
@@ -104,25 +118,29 @@ func TestConvertMapToQueryString(t *testing.T) {
}
func TestParseResponse(t *testing.T) {
url := "http://public-api-v1.aspirantzhang.com/users"
type User struct {
Id int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
url := "https://jsonplaceholder.typicode.com/todos/1"
header := map[string]string{
"Content-Type": "application/json",
}
type UserResp struct {
Data []User `json:"data"`
}
resp, err := HttpGet(url)
resp, err := HttpGet(url, header)
if err != nil {
log.Fatal(err)
t.FailNow()
}
userResp := &UserResp{}
err = ParseHttpResponse(resp, userResp)
type Todo struct {
Id int `json:"id"`
UserId int `json:"userId"`
Title string `json:"title"`
Completed bool `json:"completed"`
}
toDoResp := &Todo{}
err = ParseHttpResponse(resp, toDoResp)
if err != nil {
log.Fatal(err)
t.FailNow()
}
fmt.Println(userResp.Data)
fmt.Println("response: ", toDoResp)
}

View File

@@ -97,18 +97,18 @@ func Every(slice, function interface{}) bool {
elemType := sv.Type().Elem()
if checkSliceCallbackFuncSignature(fn, elemType, reflect.ValueOf(true).Type()) {
panic("Filter function must be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String())
panic("function param should be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String())
}
var indexes []int
var currentLength int
for i := 0; i < sv.Len(); i++ {
flag := fn.Call([]reflect.Value{reflect.ValueOf(i), sv.Index(i)})[0]
if flag.Bool() {
indexes = append(indexes, i)
currentLength++
}
}
return len(indexes) == sv.Len()
return currentLength == sv.Len()
}
// Some return true if any of the values in the list pass the predicate function.
@@ -119,7 +119,7 @@ func Some(slice, function interface{}) bool {
elemType := sv.Type().Elem()
if checkSliceCallbackFuncSignature(fn, elemType, reflect.ValueOf(true).Type()) {
panic("Filter function must be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String())
panic("function param should be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String())
}
has := false
@@ -141,7 +141,7 @@ func Filter(slice, function interface{}) interface{} {
elemType := sv.Type().Elem()
if checkSliceCallbackFuncSignature(fn, elemType, reflect.ValueOf(true).Type()) {
panic("Filter function must be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String())
panic("function param should be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String())
}
var indexes []int
@@ -167,7 +167,7 @@ func Find(slice, function interface{}) interface{} {
elemType := sv.Type().Elem()
if checkSliceCallbackFuncSignature(fn, elemType, reflect.ValueOf(true).Type()) {
panic("Filter function must be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String())
panic("function param should be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String())
}
var index int
@@ -189,7 +189,7 @@ func Map(slice, function interface{}) interface{} {
elemType := sv.Type().Elem()
if checkSliceCallbackFuncSignature(fn, elemType, nil) {
panic("Map function must be of type func(int, " + elemType.String() + ")" + elemType.String())
panic("function param should be of type func(int, " + elemType.String() + ")" + elemType.String())
}
res := reflect.MakeSlice(sv.Type(), sv.Len(), sv.Len())
@@ -215,7 +215,7 @@ func Reduce(slice, function, zero interface{}) interface{} {
fn := functionValue(function)
if checkSliceCallbackFuncSignature(fn, elementType, elementType, elementType) {
t := elementType.String()
panic("Reduce function must be of type func(int, " + t + ", " + t + ")" + t)
panic("function param should be of type func(int, " + t + ", " + t + ")" + t)
}
var params [3]reflect.Value
@@ -379,22 +379,28 @@ func Unique(slice interface{}) interface{} {
return slice
}
var res []interface{}
var temp []interface{}
len := 0
for i := 0; i < sv.Len(); i++ {
v := sv.Index(i).Interface()
flag := true
for j := range res {
if v == res[j] {
flag = false
skip := true
for j := range temp {
if v == temp[j] {
skip = false
break
}
}
if flag {
res = append(res, v)
if skip {
temp = append(temp, v)
len++
}
}
return res
res := reflect.MakeSlice(sv.Type(), len, len)
for i := 0; i < len; i++ {
res.Index(i).Set(reflect.ValueOf(temp[i]))
}
return res.Interface()
// if use map filter, the result slice element order is random, not same as origin slice
//mp := make(map[interface{}]bool)
@@ -411,6 +417,66 @@ func Unique(slice interface{}) interface{} {
}
// Union creates a slice of unique values, in order, from all given slices. using == for equality comparisons.
func Union(slices ...interface{}) interface{} {
if len(slices) == 0 {
return nil
}
// append all slices, then unique it
var allSlice []interface{}
len := 0
for i := range slices {
sv := sliceValue(slices[i])
len += sv.Len()
for j := 0; j < sv.Len(); j++ {
v := sv.Index(j).Interface()
allSlice = append(allSlice, v)
}
}
sv := sliceValue(slices[0])
res := reflect.MakeSlice(sv.Type(), len, len)
for i := 0; i < len; i++ {
res.Index(i).Set(reflect.ValueOf(allSlice[i]))
}
return Unique(res.Interface())
}
// Intersection creates a slice of unique values that included by all slices.
func Intersection(slices ...interface{}) interface{} {
if len(slices) == 0 {
return nil
}
reduceFunc := func(index int, slice1, slice2 interface{}) interface{} {
set := make([]interface{}, 0)
hash := make(map[interface{}]bool)
sv1 := reflect.ValueOf(slice1)
for i := 0; i < sv1.Len(); i++ {
v := sv1.Index(i).Interface()
hash[v] = true
}
sv2 := reflect.ValueOf(slice2)
for i := 0; i < sv2.Len(); i++ {
el := sv2.Index(i).Interface()
if _, found := hash[el]; found {
set = append(set, el)
}
}
res := reflect.MakeSlice(sv1.Type(), len(set), len(set))
for i := 0; i < len(set); i++ {
res.Index(i).Set(reflect.ValueOf(set[i]))
}
return res.Interface()
}
res := Reduce(slices, reduceFunc, nil)
return Unique(res)
}
// ReverseSlice return slice of element order is reversed to the given slice
func ReverseSlice(slice interface{}) {
v := sliceValue(slice)
@@ -474,3 +540,25 @@ func SortByField(slice interface{}, field string, sortType ...string) error {
}
return nil
}
// Without creates a slice excluding all given values
func Without(slice interface{}, values ...interface{}) interface{} {
sv := sliceValue(slice)
if sv.Len() == 0 {
return slice
}
var indexes []int
for i := 0; i < sv.Len(); i++ {
v := sv.Index(i).Interface()
if !Contain(values, v) {
indexes = append(indexes, i)
}
}
res := reflect.MakeSlice(sv.Type(), len(indexes), len(indexes))
for i := range indexes {
res.Index(i).Set(sv.Index(indexes[i]))
}
return res.Interface()
}

View File

@@ -395,7 +395,7 @@ func updateByIndex(t *testing.T, test interface{}, index int, value, expected in
func TestUnique(t *testing.T) {
t1 := []int{1, 2, 2, 3}
e1 := []int{1, 2, 3}
r1, _ := IntSlice(Unique(t1))
r1 := Unique(t1)
if !reflect.DeepEqual(r1, e1) {
utils.LogFailedTestInfo(t, "Unique", t1, e1, r1)
t.FailNow()
@@ -403,13 +403,60 @@ func TestUnique(t *testing.T) {
t2 := []string{"a", "a", "b", "c"}
e2 := []string{"a", "b", "c"}
r2 := StringSlice(Unique(t2))
r2 := Unique(t2)
if !reflect.DeepEqual(r2, e2) {
utils.LogFailedTestInfo(t, "Unique", t2, e2, r2)
t.FailNow()
}
}
func TestUnion(t *testing.T) {
s1 := []int{1, 3, 4, 6}
s2 := []int{1, 2, 5, 6}
s3 := []int{0, 4, 5, 7}
expected1 := []int{1, 3, 4, 6, 2, 5, 0, 7}
res1 := Union(s1, s2, s3)
if !reflect.DeepEqual(res1, expected1) {
utils.LogFailedTestInfo(t, "Union", s1, expected1, res1)
t.FailNow()
}
expected2 := []int{1, 3, 4, 6}
res2 := Union(s1)
if !reflect.DeepEqual(res2, expected2) {
utils.LogFailedTestInfo(t, "Union", s1, expected2, res2)
t.FailNow()
}
}
func TestIntersection(t *testing.T) {
s1 := []int{1, 2, 2, 3}
s2 := []int{1, 2, 3, 4}
s3 := []int{0, 2, 3, 5, 6}
s4 := []int{0, 5, 6}
expected := [][]int{
{2, 3},
{1, 2, 3},
{1, 2, 3},
{},
}
res := []interface{}{
Intersection(s1, s2, s3),
Intersection(s1, s2),
Intersection(s1),
Intersection(s1, s4),
}
for i := 0; i < len(res); i++ {
if !reflect.DeepEqual(res[i], expected[i]) {
utils.LogFailedTestInfo(t, "Intersection", "Intersection", expected[i], res[i])
t.FailNow()
}
}
}
func TestReverseSlice(t *testing.T) {
s1 := []int{1, 2, 3, 4, 5}
e1 := []int{5, 4, 3, 2, 1}
@@ -469,3 +516,14 @@ func TestSortByField(t *testing.T) {
}
}
func TestWithout(t *testing.T) {
s := []int{1, 2, 3, 4, 5}
expected := []int{3, 4, 5}
res := Without(s, 1, 2)
if !reflect.DeepEqual(res, expected) {
utils.LogFailedTestInfo(t, "Without", s, expected, res)
t.FailNow()
}
}

View File

@@ -7,6 +7,8 @@ package strutil
import (
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
// CamelCase covert string to camelCase string.
@@ -40,18 +42,16 @@ func Capitalize(s string) string {
return ""
}
res := ""
for i, v := range []rune(s) {
out := make([]rune, len(s))
for i, v := range s {
if i == 0 {
if v >= 97 && v <= 122 {
v -= 32
}
res += string(v)
out[i] = unicode.ToUpper(v)
} else {
res += strings.ToLower(string(v))
out[i] = unicode.ToLower(v)
}
}
return res
return string(out)
}
// LowerFirst converts the first character of string to lower case.
@@ -60,20 +60,10 @@ func LowerFirst(s string) string {
return ""
}
res := ""
for i, v := range []rune(s) {
if i == 0 {
if v >= 65 && v <= 96 {
v += 32
res += string(v)
} else {
return s
}
} else {
res += string(v)
}
}
return res
r, size := utf8.DecodeRuneInString(s)
r = unicode.ToLower(r)
return string(r) + s[size:]
}
// PadEnd pads string on the right side if it's shorter than size.

View File

@@ -70,6 +70,7 @@ func TestLowerFirst(t *testing.T) {
lowerFirst(t, "foo", "foo")
lowerFirst(t, "BAR", "bAR")
lowerFirst(t, "FOo", "fOo")
lowerFirst(t, "FOo大", "fOo大")
}
func lowerFirst(t *testing.T, test string, expected string) {

View File

@@ -11,11 +11,11 @@ import (
"unicode"
)
var isAlphaRegexMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z]+$`)
// IsAlpha checks if the string contains only letters (a-zA-Z)
func IsAlpha(s string) bool {
pattern := `^[a-zA-Z]+$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(s)
return isAlphaRegexMatcher.MatchString(s)
}
// IsNumberStr check if the string can convert to a number.
@@ -29,10 +29,11 @@ func IsFloatStr(s string) bool {
return e == nil
}
var isIntStrRegexMatcher *regexp.Regexp = regexp.MustCompile(`^[\+-]?\d+$`)
// IsIntStr check if the string can convert to a integer.
func IsIntStr(s string) bool {
match, _ := regexp.MatchString(`^[\+-]?\d+$`, s)
return match
return isIntStrRegexMatcher.MatchString(s)
}
// IsIp check if the string is a ip address.
@@ -71,61 +72,61 @@ func IsIpV6(ipstr string) bool {
return false
}
var isDnsRegexMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z]([a-zA-Z0-9\-]+[\.]?)*[a-zA-Z0-9]$`)
// IsDns check if the string is dns.
func IsDns(dns string) bool {
pattern := `^[a-zA-Z]([a-zA-Z0-9\-]+[\.]?)*[a-zA-Z0-9]$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(dns)
return isDnsRegexMatcher.MatchString(dns)
}
var isEmailRegexMatcher *regexp.Regexp = regexp.MustCompile(`\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*`)
// IsEmail check if the string is a email address.
func IsEmail(email string) bool {
pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*`
reg := regexp.MustCompile(pattern)
return reg.MatchString(email)
return isEmailRegexMatcher.MatchString(email)
}
var isChineseMobileRegexMatcher *regexp.Regexp = regexp.MustCompile("^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$")
// IsChineseMobile check if the string is chinese mobile number.
func IsChineseMobile(mobileNum string) bool {
pattern := "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$"
reg := regexp.MustCompile(pattern)
return reg.MatchString(mobileNum)
return isChineseMobileRegexMatcher.MatchString(mobileNum)
}
var isChineseIdNumRegexMatcher *regexp.Regexp = regexp.MustCompile(`^[1-9]\d{5}(18|19|20|21|22)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$`)
// IsChineseIdNum check if the string is chinese id number.
func IsChineseIdNum(id string) bool {
pattern := `^[1-9]\d{5}(18|19|20|21|22)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(id)
return isChineseIdNumRegexMatcher.MatchString(id)
}
var containChineseRegexMatcher *regexp.Regexp = regexp.MustCompile("[\u4e00-\u9fa5]")
// ContainChinese check if the string contain mandarin chinese.
func ContainChinese(s string) bool {
pattern := "[\u4e00-\u9fa5]"
reg := regexp.MustCompile(pattern)
return reg.MatchString(s)
return containChineseRegexMatcher.MatchString(s)
}
var isChinesePhoneRegexMatcher *regexp.Regexp = regexp.MustCompile(`\d{3}-\d{8}|\d{4}-\d{7}`)
// IsChinesePhone check if the string is chinese phone number.
// Valid chinese phone is xxx-xxxxxxxx or xxxx-xxxxxxx
func IsChinesePhone(phone string) bool {
pattern := `\d{3}-\d{8}|\d{4}-\d{7}`
reg := regexp.MustCompile(pattern)
return reg.MatchString(phone)
return isChinesePhoneRegexMatcher.MatchString(phone)
}
var isCreditCardRegexMatcher *regexp.Regexp = regexp.MustCompile(`^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27][0-9]{14})$`)
// IsCreditCard check if the string is credit card.
func IsCreditCard(creditCart string) bool {
pattern := `^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27][0-9]{14})$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(creditCart)
return isCreditCardRegexMatcher.MatchString(creditCart)
}
var isBase64RegexMatcher *regexp.Regexp = regexp.MustCompile(`^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$`)
// IsBase64 check if the string is base64 string.
func IsBase64(base64 string) bool {
pattern := `^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(base64)
return isBase64RegexMatcher.MatchString(base64)
}
// IsEmptyString check if the string is empty.