mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-05 21:32:27 +08:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8bb102cb6e | ||
|
|
e07d54d1da | ||
|
|
6f035f710e | ||
|
|
92967e0add | ||
|
|
6a1a0b8677 | ||
|
|
ca88687f3d | ||
|
|
aa64bf5bee | ||
|
|
a3399503f7 | ||
|
|
3ca096b4ac | ||
|
|
28317a1683 | ||
|
|
2ab898741d | ||
|
|
454efd486d |
@@ -4,7 +4,7 @@
|
||||
</p>
|
||||
|
||||

|
||||
[](https://github.com/duke-git/lancet/releases)
|
||||
[](https://github.com/duke-git/lancet/releases)
|
||||
[](https://pkg.go.dev/github.com/duke-git/lancet)
|
||||
[](https://goreportcard.com/report/github.com/duke-git/lancet)
|
||||
[](https://github.com/duke-git/lancet/actions/workflows/codecov.yml)
|
||||
@@ -278,6 +278,7 @@ func After(n int, fn interface{}) func(args ...interface{}) []reflect.Value //c
|
||||
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 Debounced(fn func(), duration time.Duration) func() //creates a debounced function that delays invoking fn until after wait duration have elapsed since the last time the debounced function was invoked.
|
||||
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
|
||||
func (w *Watcher) Start() //start the watch timer.
|
||||
@@ -434,8 +435,10 @@ func main() {
|
||||
func Contain(slice interface{}, value interface{}) bool //check if the value is in the slice or not
|
||||
func ContainSubSlice(slice interface{}, subslice interface{}) bool //check if the slice contain subslice or not
|
||||
func Chunk(slice []interface{}, size int) [][]interface{} //creates an slice of elements split into groups the length of `size`
|
||||
func ConvertSlice(originalSlice interface{}, newSliceType reflect.Type) interface{} //convert originalSlice to newSliceType
|
||||
func Compact(slice interface{}) interface{} //creates an slice with all falsey values removed. The values false, nil, 0, and "" are falsey
|
||||
func Concat(slice interface{}, values ...interface{}) interface{} //creates a new slice concatenating slice with any additional slices and/or values
|
||||
func Difference(slice1, slice2 interface{}) interface{} //creates an slice of whose element not included in the other given slice
|
||||
func DifferenceBy(slice interface{}, comparedSlice interface{}, iterateeFn interface{}) interface{} //it accepts iteratee which is invoked for each element of slice and values to generate the criterion by which they're compared.
|
||||
func DeleteByIndex(slice interface{}, start int, end ...int) (interface{}, error) //delete the element of slice from start index to end index - 1
|
||||
func Drop(slice interface{}, n int) interface{} //creates a slice with `n` elements dropped from the beginning when n > 0, or `n` elements dropped from the ending when n < 0
|
||||
func Every(slice, function interface{}) bool //return true if all of the values in the slice pass the predicate function, function signature should be func(index int, value interface{}) bool
|
||||
@@ -497,6 +500,7 @@ func Capitalize(s string) string //convert the first character of a string to up
|
||||
func IsString(v interface{}) bool //check if the value data type is string or not
|
||||
func KebabCase(s string) string //covert string to kebab-case, "foo_Bar" -> "foo-bar"
|
||||
func LowerFirst(s string) string //convert the first character of string to lower case
|
||||
func UpperFirst(s string) string //converts the first character of string to upper case
|
||||
func PadEnd(source string, size int, padStr string) string //pads string on the right side if it's shorter than size
|
||||
func PadStart(source string, size int, padStr string) string//pads string on the left side if it's shorter than size
|
||||
func ReverseStr(s string) string //return string whose char order is reversed to the given string
|
||||
@@ -587,5 +591,6 @@ func IsIp(ipstr string) bool //check if the string is a ip address
|
||||
func IsIpV4(ipstr string) bool //check if the string is a ipv4 address
|
||||
func IsIpV6(ipstr string) bool //check if the string is a ipv6 address
|
||||
func IsStrongPassword(password string, length int) bool //check if the string is strong password (alpha(lower+upper) + number + special chars(!@#$%^&*()?><))
|
||||
func IsUrl(str string) bool //check if the string is url
|
||||
func IsWeakPassword(password string) bool //check if the string is weak password(only letter or only number or letter + number)
|
||||
```
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
</p>
|
||||
|
||||

|
||||
[](https://github.com/duke-git/lancet/releases)
|
||||
[](https://github.com/duke-git/lancet/releases)
|
||||
[](https://pkg.go.dev/github.com/duke-git/lancet)
|
||||
[](https://goreportcard.com/report/github.com/duke-git/lancet)
|
||||
[](https://github.com/duke-git/lancet/actions/workflows/codecov.yml)
|
||||
@@ -279,6 +279,7 @@ func Before(n int, fn interface{}) func(args ...interface{}) []reflect.Value //
|
||||
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 Debounced(fn func(), duration time.Duration) func() //go防抖函数,在duration时间内连续调用只会执行一次.
|
||||
func Schedule(d time.Duration, fn interface{}, args ...interface{}) chan bool //每隔duration时间调用函数, 关闭返回通道可以停止调用
|
||||
func (w *Watcher) Start() //开时watcher
|
||||
func (w *Watcher) Stop() //开时watcher
|
||||
@@ -434,8 +435,10 @@ func main() {
|
||||
func Contain(slice interface{}, value interface{}) bool //判断slice是否包含value
|
||||
func ContainSubSlice(slice interface{}, subslice interface{}) bool //判断slice是否包含subslice
|
||||
func Chunk(slice []interface{}, size int) [][]interface{} //均分slice
|
||||
func ConvertSlice(originalSlice interface{}, newSliceType reflect.Type) interface{} //将originalSlice转换为 newSliceType
|
||||
func Compact(slice interface{}) interface{} //去除slice中的false vule. false values are false, nil, 0, and ""
|
||||
func Concat(slice interface{}, values ...interface{}) interface{} //连接values到slice中
|
||||
func Difference(slice1, slice2 interface{}) interface{} //返回切片,其元素在slice1中,不在slice2中
|
||||
func DifferenceBy(slice interface{}, comparedSlice interface{}, iterateeFn interface{}) interface{} //将slice 和comparedSlice中每个元素调用iterateeFn后作比较,如果不相等返回slice中的元素。
|
||||
func DeleteByIndex(slice interface{}, start int, end ...int) (interface{}, error) //删除切片中start到end位置的值
|
||||
func Drop(slice interface{}, n int) interface{} //创建一个新切片,当n大于0时删除原切片前n个元素,当n小于0时删除原切片后n个元素
|
||||
func Every(slice, function interface{}) bool //slice中所有元素都符合函数条件时返回true, 否则返回false. 函数签名:func(index int, value interface{}) bool
|
||||
@@ -496,6 +499,7 @@ func CamelCase(s string) string //字符串转为cameCase, "foo bar" -> "fooBar"
|
||||
func Capitalize(s string) string //字符串转为Capitalize, "fOO" -> "Foo"
|
||||
func IsString(v interface{}) bool //判断是否是字符串
|
||||
func KebabCase(s string) string //字符串转为KebabCase, "foo_Bar" -> "foo-bar"
|
||||
func UpperFirst(s string) string //字符串的第一个字母转为大写字母
|
||||
func LowerFirst(s string) string //字符串的第一个字母转为小写字母
|
||||
func PadEnd(source string, size int, padStr string) string //字符串末尾填充size个字符
|
||||
func PadStart(source string, size int, padStr string) string//字符串开头填充size个字符
|
||||
@@ -588,5 +592,6 @@ func IsIp(ipstr string) bool //判断字符串是否是ip
|
||||
func IsIpV4(ipstr string) bool //判断字符串是否是ipv4
|
||||
func IsIpV6(ipstr string) bool //判断字符串是否是ipv6
|
||||
func IsStrongPassword(password string, length int) bool //判断字符串是否是强密码(大小写字母+数字+特殊字符)
|
||||
func IsUrl(str string) bool //判断字符串是否是url
|
||||
func IsWeakPassword(password string) bool //判断字符串是否是弱密码(只有字母或数字)
|
||||
```
|
||||
|
||||
@@ -262,7 +262,7 @@ func FileMode(path string) (fs.FileMode, error) {
|
||||
}
|
||||
|
||||
// MiMeType return file mime type
|
||||
// file should be string or *os.File
|
||||
// param `file` should be string(file path) or *os.File
|
||||
func MiMeType(file interface{}) string {
|
||||
var mediatype string
|
||||
|
||||
|
||||
@@ -70,6 +70,23 @@ func Delay(delay time.Duration, fn interface{}, args ...interface{}) {
|
||||
invokeFunc(fn, args...)
|
||||
}
|
||||
|
||||
// Debounced creates a debounced function that delays invoking fn until after wait duration have elapsed since the last time the debounced function was invoked.
|
||||
func Debounced(fn func(), duration time.Duration) func() {
|
||||
timer := time.NewTimer(duration)
|
||||
timer.Stop()
|
||||
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-timer.C:
|
||||
go fn()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return func() { timer.Reset(duration) }
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
@@ -93,6 +93,28 @@ func TestDelay(t *testing.T) {
|
||||
Delay(2*time.Second, print, "test delay")
|
||||
}
|
||||
|
||||
func TestDebounced(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestDebounced")
|
||||
|
||||
count := 0
|
||||
add := func() {
|
||||
count++
|
||||
}
|
||||
|
||||
debouncedAdd := Debounced(add, 50*time.Microsecond)
|
||||
debouncedAdd()
|
||||
debouncedAdd()
|
||||
debouncedAdd()
|
||||
debouncedAdd()
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
assert.Equal(1, count)
|
||||
|
||||
debouncedAdd()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
assert.Equal(2, count)
|
||||
}
|
||||
|
||||
func TestSchedule(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSchedule")
|
||||
|
||||
|
||||
@@ -8,11 +8,31 @@ func TestAssert(t *testing.T) {
|
||||
assert := NewAssert(t, "TestAssert")
|
||||
assert.Equal(0, 0)
|
||||
assert.NotEqual(1, 0)
|
||||
|
||||
assert.NotEqual("1", 1)
|
||||
var uInt1 uint
|
||||
var uInt2 uint
|
||||
var uInt8 uint8
|
||||
var uInt16 uint16
|
||||
var uInt32 uint32
|
||||
var uInt64 uint64
|
||||
assert.NotEqual(uInt1, uInt8)
|
||||
assert.NotEqual(uInt8, uInt16)
|
||||
assert.NotEqual(uInt16, uInt32)
|
||||
assert.NotEqual(uInt32, uInt64)
|
||||
|
||||
assert.Equal(uInt1, uInt2)
|
||||
|
||||
uInt1 = 1
|
||||
uInt2 = 2
|
||||
assert.Less(uInt1, uInt2)
|
||||
|
||||
assert.Greater(1, 0)
|
||||
assert.GreaterOrEqual(1, 1)
|
||||
assert.Less(0, 1)
|
||||
assert.LessOrEqual(0, 0)
|
||||
|
||||
assert.Equal(0.1, 0.1)
|
||||
assert.Greater(1.1, 0.1)
|
||||
assert.Less(0.1, 1.1)
|
||||
|
||||
|
||||
119
slice/slice.go
119
slice/slice.go
@@ -12,7 +12,6 @@ import (
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Contain check if the value is in the iterable type or not
|
||||
@@ -103,25 +102,107 @@ func Chunk(slice []interface{}, size int) [][]interface{} {
|
||||
return res
|
||||
}
|
||||
|
||||
// Difference creates an slice of whose element not included in the other given slice
|
||||
func Difference(slice1, slice2 interface{}) interface{} {
|
||||
v := sliceValue(slice1)
|
||||
// Compact creates an slice with all falsey values removed. The values false, nil, 0, and "" are falsey
|
||||
func Compact(slice interface{}) interface{} {
|
||||
sv := sliceValue(slice)
|
||||
|
||||
var indexes []int
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
vi := v.Index(i).Interface()
|
||||
if !Contain(slice2, vi) {
|
||||
for i := 0; i < sv.Len(); i++ {
|
||||
item := sv.Index(i).Interface()
|
||||
if item != nil && item != false && item != "" && item != 0 {
|
||||
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()
|
||||
}
|
||||
|
||||
// Concat creates a new slice concatenating slice with any additional slices and/or values.
|
||||
func Concat(slice interface{}, values ...interface{}) interface{} {
|
||||
sv := sliceValue(slice)
|
||||
size := sv.Len()
|
||||
|
||||
res := reflect.MakeSlice(sv.Type(), size, size)
|
||||
for i := 0; i < size; i++ {
|
||||
res.Index(i).Set(sv.Index(i))
|
||||
}
|
||||
|
||||
for _, v := range values {
|
||||
if reflect.TypeOf(v).Kind() == reflect.Slice {
|
||||
vv := reflect.ValueOf(v)
|
||||
for i := 0; i < vv.Len(); i++ {
|
||||
res = reflect.Append(res, vv.Index(i))
|
||||
}
|
||||
} else {
|
||||
res = reflect.Append(res, reflect.ValueOf(v))
|
||||
}
|
||||
}
|
||||
|
||||
return res.Interface()
|
||||
}
|
||||
|
||||
// Difference creates an slice of whose element in slice1, not in slice2
|
||||
func Difference(slice1, slice2 interface{}) interface{} {
|
||||
sv := sliceValue(slice1)
|
||||
|
||||
var indexes []int
|
||||
for i := 0; i < sv.Len(); i++ {
|
||||
item := sv.Index(i).Interface()
|
||||
if !Contain(slice2, item) {
|
||||
indexes = append(indexes, i)
|
||||
}
|
||||
}
|
||||
|
||||
res := reflect.MakeSlice(v.Type(), len(indexes), len(indexes))
|
||||
res := reflect.MakeSlice(sv.Type(), len(indexes), len(indexes))
|
||||
for i := range indexes {
|
||||
res.Index(i).Set(v.Index(indexes[i]))
|
||||
res.Index(i).Set(sv.Index(indexes[i]))
|
||||
}
|
||||
return res.Interface()
|
||||
}
|
||||
|
||||
// DifferenceBy it accepts iteratee which is invoked for each element of slice
|
||||
// and values to generate the criterion by which they're compared.
|
||||
// like lodash.js differenceBy: https://lodash.com/docs/4.17.15#differenceBy,
|
||||
// the iterateeFn function signature should be func(index int, value interface{}) interface{}.
|
||||
func DifferenceBy(slice interface{}, comparedSlice interface{}, iterateeFn interface{}) interface{} {
|
||||
sv := sliceValue(slice)
|
||||
smv := sliceValue(comparedSlice)
|
||||
fn := functionValue(iterateeFn)
|
||||
|
||||
elemType := sv.Type().Elem()
|
||||
if checkSliceCallbackFuncSignature(fn, elemType, nil) {
|
||||
panic("function param should be of type func(" + elemType.String() + ")" + elemType.String())
|
||||
}
|
||||
|
||||
slice1 := reflect.MakeSlice(sv.Type(), sv.Len(), sv.Len())
|
||||
for i := 0; i < sv.Len(); i++ {
|
||||
slice1.Index(i).Set(fn.Call([]reflect.Value{reflect.ValueOf(i), sv.Index(i)})[0])
|
||||
}
|
||||
|
||||
slice2 := reflect.MakeSlice(smv.Type(), smv.Len(), smv.Len())
|
||||
for i := 0; i < smv.Len(); i++ {
|
||||
slice2.Index(i).Set(fn.Call([]reflect.Value{reflect.ValueOf(i), smv.Index(i)})[0])
|
||||
}
|
||||
|
||||
sliceAfterMap := slice1.Interface()
|
||||
comparedSliceAfterMap := slice2.Interface()
|
||||
|
||||
res := reflect.MakeSlice(sv.Type(), 0, 0)
|
||||
sm := sliceValue(sliceAfterMap)
|
||||
for i := 0; i < sm.Len(); i++ {
|
||||
item := sm.Index(i).Interface()
|
||||
if !Contain(comparedSliceAfterMap, item) {
|
||||
res = reflect.Append(res, sv.Index(i))
|
||||
}
|
||||
}
|
||||
|
||||
return res.Interface()
|
||||
}
|
||||
|
||||
// Every return true if all of the values in the slice pass the predicate function.
|
||||
// The function signature should be func(index int, value interface{}) bool .
|
||||
func Every(slice, function interface{}) bool {
|
||||
@@ -427,26 +508,6 @@ func IntSlice(slice interface{}) []int {
|
||||
return out
|
||||
}
|
||||
|
||||
// ConvertSlice convert original slice to new data type element of slice.
|
||||
func ConvertSlice(originalSlice interface{}, newSliceType reflect.Type) interface{} {
|
||||
sv := sliceValue(originalSlice)
|
||||
if newSliceType.Kind() != reflect.Slice {
|
||||
panic(fmt.Sprintf("Invalid newSliceType(non-slice type of type %T)", newSliceType))
|
||||
}
|
||||
|
||||
newSlice := reflect.New(newSliceType)
|
||||
|
||||
hdr := (*reflect.SliceHeader)(unsafe.Pointer(newSlice.Pointer()))
|
||||
|
||||
var newElemSize = int(sv.Type().Elem().Size()) / int(newSliceType.Elem().Size())
|
||||
|
||||
hdr.Cap = sv.Cap() * newElemSize
|
||||
hdr.Len = sv.Len() * newElemSize
|
||||
hdr.Data = sv.Pointer()
|
||||
|
||||
return newSlice.Elem().Interface()
|
||||
}
|
||||
|
||||
// DeleteByIndex delete the element of slice from start index to end index - 1.
|
||||
// Delete i: s = append(s[:i], s[i+1:]...)
|
||||
// Delete i to j: s = append(s[:i], s[j:]...)
|
||||
|
||||
@@ -36,55 +36,41 @@ func TestChunk(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestChunk")
|
||||
|
||||
arr := []string{"a", "b", "c", "d", "e"}
|
||||
r1 := [][]interface{}{
|
||||
{"a"},
|
||||
{"b"},
|
||||
{"c"},
|
||||
{"d"},
|
||||
{"e"},
|
||||
}
|
||||
r1 := [][]interface{}{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}}
|
||||
assert.Equal(r1, Chunk(InterfaceSlice(arr), 1))
|
||||
|
||||
r2 := [][]interface{}{
|
||||
{"a", "b"},
|
||||
{"c", "d"},
|
||||
{"e"},
|
||||
}
|
||||
r2 := [][]interface{}{{"a", "b"}, {"c", "d"}, {"e"}}
|
||||
assert.Equal(r2, Chunk(InterfaceSlice(arr), 2))
|
||||
|
||||
r3 := [][]interface{}{
|
||||
{"a", "b", "c"},
|
||||
{"d", "e"},
|
||||
}
|
||||
r3 := [][]interface{}{{"a", "b", "c"}, {"d", "e"}}
|
||||
assert.Equal(r3, Chunk(InterfaceSlice(arr), 3))
|
||||
|
||||
r4 := [][]interface{}{
|
||||
{"a", "b", "c", "d"},
|
||||
{"e"},
|
||||
}
|
||||
r4 := [][]interface{}{{"a", "b", "c", "d"}, {"e"}}
|
||||
assert.Equal(r4, Chunk(InterfaceSlice(arr), 4))
|
||||
|
||||
r5 := [][]interface{}{
|
||||
{"a"},
|
||||
{"b"},
|
||||
{"c"},
|
||||
{"d"},
|
||||
{"e"},
|
||||
}
|
||||
r5 := [][]interface{}{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}}
|
||||
assert.Equal(r5, Chunk(InterfaceSlice(arr), 5))
|
||||
}
|
||||
|
||||
func TestConvertSlice(t *testing.T) {
|
||||
//t1 := []string{"1","2"}
|
||||
//aInt, _ := strconv.ParseInt("1", 10, 64)
|
||||
//bInt, _ := strconv.ParseInt("2", 10, 64)
|
||||
//expected :=[]int64{aInt, bInt}
|
||||
//
|
||||
//a := ConvertSlice(t1, reflect.TypeOf(expected))
|
||||
//if !reflect.DeepEqual(a, expected) {
|
||||
// utils.LogFailedTestInfo(t, "ConvertSlice", t1, expected, a)
|
||||
// t.FailNow()
|
||||
//}
|
||||
func TestCompact(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TesCompact")
|
||||
|
||||
assert.Equal([]int{}, Compact([]int{0}))
|
||||
assert.Equal([]int{1, 2, 3}, Compact([]int{0, 1, 2, 3}))
|
||||
assert.Equal([]string{}, Compact([]string{""}))
|
||||
assert.Equal([]string{" "}, Compact([]string{" "}))
|
||||
assert.Equal([]string{"a", "b", "0"}, Compact([]string{"", "a", "b", "0"}))
|
||||
assert.Equal([]bool{true, true}, Compact([]bool{false, true, true}))
|
||||
}
|
||||
|
||||
func TestConcat(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "Concat")
|
||||
|
||||
assert.Equal([]int{0}, Concat([]int{}, 0))
|
||||
assert.Equal([]int{1, 2, 3, 4, 5}, Concat([]int{1, 2, 3}, 4, 5))
|
||||
assert.Equal([]int{1, 2, 3, 4, 5}, Concat([]int{1, 2, 3}, []int{4, 5}))
|
||||
assert.Equal([]int{1, 2, 3, 4, 5}, Concat([]int{1, 2, 3}, []int{4}, []int{5}))
|
||||
assert.Equal([]int{1, 2, 3, 4, 5}, Concat([]int{1, 2, 3}, []int{4}, 5))
|
||||
}
|
||||
|
||||
func TestEvery(t *testing.T) {
|
||||
@@ -430,6 +416,7 @@ func TestIntersection(t *testing.T) {
|
||||
for i := 0; i < len(res); i++ {
|
||||
assert.Equal(res[i], expected[i])
|
||||
}
|
||||
assert.IsNil(Intersection())
|
||||
}
|
||||
|
||||
func TestReverseSlice(t *testing.T) {
|
||||
@@ -452,6 +439,17 @@ func TestDifference(t *testing.T) {
|
||||
assert.Equal([]int{1, 2, 3}, Difference(s1, s2))
|
||||
}
|
||||
|
||||
func TestDifferenceBy(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestDifferenceBy")
|
||||
|
||||
s1 := []int{1, 2, 3, 4, 5} //after add one: 2 3 4 5 6
|
||||
s2 := []int{3, 4, 5} //after add one: 4 5 6
|
||||
addOne := func(i int, v int) int {
|
||||
return v + 1
|
||||
}
|
||||
assert.Equal([]int{1, 2}, DifferenceBy(s1, s2, addOne))
|
||||
}
|
||||
|
||||
func TestSortByFielDesc(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestWithout")
|
||||
|
||||
|
||||
@@ -54,6 +54,18 @@ func Capitalize(s string) string {
|
||||
return string(out)
|
||||
}
|
||||
|
||||
// UpperFirst converts the first character of string to upper case.
|
||||
func UpperFirst(s string) string {
|
||||
if len(s) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
r, size := utf8.DecodeRuneInString(s)
|
||||
r = unicode.ToUpper(r)
|
||||
|
||||
return string(r) + s[size:]
|
||||
}
|
||||
|
||||
// LowerFirst converts the first character of string to lower case.
|
||||
func LowerFirst(s string) string {
|
||||
if len(s) == 0 {
|
||||
|
||||
@@ -50,6 +50,17 @@ func TestSnakeCase(t *testing.T) {
|
||||
assert.NotEqual("foo-bar", SnakeCase("foo_Bar"))
|
||||
}
|
||||
|
||||
func TestUpperFirst(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestLowerFirst")
|
||||
|
||||
assert.Equal("Foo", UpperFirst("foo"))
|
||||
assert.Equal("BAR", UpperFirst("bAR"))
|
||||
assert.Equal("FOo", UpperFirst("FOo"))
|
||||
assert.Equal("FOo大", UpperFirst("fOo大"))
|
||||
|
||||
assert.NotEqual("Bar", UpperFirst("BAR"))
|
||||
}
|
||||
|
||||
func TestLowerFirst(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestLowerFirst")
|
||||
|
||||
|
||||
@@ -56,6 +56,9 @@ func ExecCommand(command string) (stdout, stderr string, err error) {
|
||||
var errout bytes.Buffer
|
||||
|
||||
cmd := exec.Command("/bin/bash", "-c", command)
|
||||
if IsWindows() {
|
||||
cmd = exec.Command("cmd")
|
||||
}
|
||||
cmd.Stdout = &out
|
||||
cmd.Stderr = &errout
|
||||
err = cmd.Run()
|
||||
|
||||
@@ -1,11 +1,24 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/duke-git/lancet/internal"
|
||||
)
|
||||
|
||||
func TestOsDetection(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestOsJudgment")
|
||||
|
||||
osType, _, _ := ExecCommand("echo $OSTYPE")
|
||||
if strings.Index(osType, "linux") != -1 {
|
||||
assert.Equal(true, IsLinux())
|
||||
}
|
||||
if strings.Index(osType, "darwin") != -1 {
|
||||
assert.Equal(true, IsMac())
|
||||
}
|
||||
}
|
||||
|
||||
func TestOsEnvOperation(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestOsEnvOperation")
|
||||
|
||||
@@ -18,6 +31,14 @@ func TestOsEnvOperation(t *testing.T) {
|
||||
|
||||
assert.Equal(true, CompareOsEnv("foo", "foo_value"))
|
||||
assert.Equal(false, CompareOsEnv("foo", "abc"))
|
||||
assert.Equal(false, CompareOsEnv("abc", "abc"))
|
||||
assert.Equal(false, CompareOsEnv("abc", "abc"))
|
||||
|
||||
err := RemoveOsEnv("foo")
|
||||
if err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
assert.Equal(false, CompareOsEnv("foo", "foo_value"))
|
||||
}
|
||||
|
||||
func TestExecCommand(t *testing.T) {
|
||||
@@ -35,5 +56,7 @@ func TestExecCommand(t *testing.T) {
|
||||
t.Logf("error: %v\n", err)
|
||||
}
|
||||
|
||||
assert.IsNotNil(err)
|
||||
if !IsWindows() {
|
||||
assert.IsNotNil(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ package validator
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -123,6 +124,27 @@ func IsPort(str string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
var isUrlRegexMatcher *regexp.Regexp = regexp.MustCompile(`^((ftp|http|https?):\/\/)?(\S+(:\S*)?@)?((([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(([a-zA-Z0-9]+([-\.][a-zA-Z0-9]+)*)|((www\.)?))?(([a-z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-z\x{00a1}-\x{ffff}]{2,}))?))(:(\d{1,5}))?((\/|\?|#)[^\s]*)?$`)
|
||||
|
||||
// IsUrl check if the string is url.
|
||||
func IsUrl(str string) bool {
|
||||
if str == "" || len(str) >= 2083 || len(str) <= 3 || strings.HasPrefix(str, ".") {
|
||||
return false
|
||||
}
|
||||
u, err := url.Parse(str)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(u.Host, ".") {
|
||||
return false
|
||||
}
|
||||
if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) {
|
||||
return false
|
||||
}
|
||||
|
||||
return isUrlRegexMatcher.MatchString(str)
|
||||
}
|
||||
|
||||
var isDnsRegexMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z]([a-zA-Z0-9\-]+[\.]?)*[a-zA-Z0-9]$`)
|
||||
|
||||
// IsDns check if the string is dns.
|
||||
|
||||
@@ -160,11 +160,21 @@ func TestIsIpV6(t *testing.T) {
|
||||
assert.Equal(true, IsIpV6("::0:0:0:0:0:0:1"))
|
||||
}
|
||||
|
||||
func TestIsUrl(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestIsUrl")
|
||||
|
||||
assert.Equal(true, IsUrl("http://abc.com"))
|
||||
assert.Equal(true, IsUrl("abc.com"))
|
||||
assert.Equal(true, IsUrl("a.b.com"))
|
||||
assert.Equal(false, IsUrl("abc"))
|
||||
}
|
||||
|
||||
func TestIsDns(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestIsDns")
|
||||
|
||||
assert.Equal(true, IsDns("abc.com"))
|
||||
assert.Equal(false, IsDns("a.b.com"))
|
||||
assert.Equal(false, IsDns("http://abc.com"))
|
||||
}
|
||||
|
||||
func TestIsEmail(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user