mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-14 01:32:27 +08:00
Compare commits
43 Commits
v2.1.10
...
2725575d2f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2725575d2f | ||
|
|
037d2729ce | ||
|
|
09d98745b0 | ||
|
|
af5cfe6da1 | ||
|
|
d59259bbe0 | ||
|
|
3189628d54 | ||
|
|
62c5e251a5 | ||
|
|
6e6444c8c0 | ||
|
|
dd613e98b2 | ||
|
|
2d905ab03e | ||
|
|
205fedb197 | ||
|
|
4c864da62d | ||
|
|
263ab7e316 | ||
|
|
809b7a53df | ||
|
|
61c43daabb | ||
|
|
18914ee2cd | ||
|
|
0a8058956f | ||
|
|
a044da7d2f | ||
|
|
f8b785c4cb | ||
|
|
82c8a04c35 | ||
|
|
280ecb5cef | ||
|
|
ec27ad4c40 | ||
|
|
d66f92cd68 | ||
|
|
d8ed692651 | ||
|
|
a16de97d1d | ||
|
|
6f458e4367 | ||
|
|
37c7508ad0 | ||
|
|
acb5844b15 | ||
|
|
76f4eeea16 | ||
|
|
5466a23019 | ||
|
|
5692982dd1 | ||
|
|
c39c8914fb | ||
|
|
29bdca1bd2 | ||
|
|
eb66d038ac | ||
|
|
a99ada5ee1 | ||
|
|
a87faf5453 | ||
|
|
ab6fec2f69 | ||
|
|
7b290989f5 | ||
|
|
5722c724e6 | ||
|
|
f84584ca04 | ||
|
|
80cbbdc787 | ||
|
|
be148e07ba | ||
|
|
d36ab5cc3a |
25
README.md
25
README.md
@@ -4,7 +4,7 @@
|
||||
<br/>
|
||||
|
||||

|
||||
[](https://github.com/duke-git/lancet/releases)
|
||||
[](https://github.com/duke-git/lancet/releases)
|
||||
[](https://pkg.go.dev/github.com/duke-git/lancet/v2)
|
||||
[](https://goreportcard.com/report/github.com/duke-git/lancet/v2)
|
||||
[](https://github.com/duke-git/lancet/actions/workflows/codecov.yml)
|
||||
@@ -372,11 +372,11 @@ import "github.com/duke-git/lancet/v2/netutil"
|
||||
- [DecodeResponse](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#DecodeResponse)
|
||||
- [StructToUrlValues](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#StructToUrlValues)
|
||||
|
||||
- [HttpGet<sup>Deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpGet)
|
||||
- [HttpDelete<sup>Deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpDelete)
|
||||
- [HttpPost<sup>Deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPost)
|
||||
- [HttpPut<sup>Deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPut)
|
||||
- [HttpPatch<sup>Deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPatch)
|
||||
- [HttpGet<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpGet)
|
||||
- [HttpDelete<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpDelete)
|
||||
- [HttpPost<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPost)
|
||||
- [HttpPut<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPut)
|
||||
- [HttpPatch<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPatch)
|
||||
- [ParseHttpResponse](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#ParseHttpResponse)
|
||||
|
||||
### 14. Random package implements some basic functions to generate random int and string.
|
||||
@@ -425,6 +425,7 @@ import "github.com/duke-git/lancet/v2/slice"
|
||||
- [Compact](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Compact)
|
||||
- [Concat](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Concat)
|
||||
- [Count](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Count)
|
||||
- [CountBy](https://github.com/duke-git/lancet/blob/main/docs/slice.md#CountBy)
|
||||
- [Difference](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Difference)
|
||||
- [DifferenceBy](https://github.com/duke-git/lancet/blob/main/docs/slice.md#DifferenceBy)
|
||||
- [DifferenceWith](https://github.com/duke-git/lancet/blob/main/docs/slice.md#DifferenceWith)
|
||||
@@ -441,21 +442,25 @@ import "github.com/duke-git/lancet/v2/slice"
|
||||
- [ForEach](https://github.com/duke-git/lancet/blob/main/docs/slice.md#ForEach)
|
||||
- [GroupBy](https://github.com/duke-git/lancet/blob/main/docs/slice.md#GroupBy)
|
||||
- [GroupWith](https://github.com/duke-git/lancet/blob/main/docs/slice.md#GroupWith)
|
||||
- [IntSlice](https://github.com/duke-git/lancet/blob/main/docs/slice.md#IntSlice)
|
||||
- [InterfaceSlice](https://github.com/duke-git/lancet/blob/main/docs/slice.md#InterfaceSlice)
|
||||
- [IntSlice<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/slice.md#IntSlice)
|
||||
- [InterfaceSlice<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/slice.md#InterfaceSlice)
|
||||
- [Intersection](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Intersection)
|
||||
- [InsertAt](https://github.com/duke-git/lancet/blob/main/docs/slice.md#InsertAt)
|
||||
- [IndexOf](https://github.com/duke-git/lancet/blob/main/docs/slice.md#IndexOf)
|
||||
- [LastIndexOf](https://github.com/duke-git/lancet/blob/main/docs/slice.md#LastIndexOf)
|
||||
- [Map](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Map)
|
||||
- [Merge](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Merge)
|
||||
- [Reverse](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Reverse)
|
||||
- [Reduce](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Reduce)
|
||||
- [Replace](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Replace)
|
||||
- [ReplaceAll](https://github.com/duke-git/lancet/blob/main/docs/slice.md#ReplaceAll)
|
||||
- [Repeat](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Repeat)
|
||||
- [Shuffle](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Shuffle)
|
||||
- [SortByField](https://github.com/duke-git/lancet/blob/main/docs/slice.md#SortByField)
|
||||
- [Sort](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Sort)
|
||||
- [SortBy](https://github.com/duke-git/lancet/blob/main/docs/slice.md#SortBy)
|
||||
- [SortByField<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/slice.md#SortByField)
|
||||
- [Some](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Some)
|
||||
- [StringSlice](https://github.com/duke-git/lancet/blob/main/docs/slice.md#StringSlice)
|
||||
- [StringSlice<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/slice.md#StringSlice)
|
||||
- [SymmetricDifference](https://github.com/duke-git/lancet/blob/main/docs/slice.md#SymmetricDifference)
|
||||
- [ToSlice](https://github.com/duke-git/lancet/blob/main/docs/slice.md#ToSlice)
|
||||
- [ToSlicePointer](https://github.com/duke-git/lancet/blob/main/docs/slice.md#ToSlicePointer)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<br/>
|
||||
|
||||

|
||||
[](https://github.com/duke-git/lancet/releases)
|
||||
[](https://github.com/duke-git/lancet/releases)
|
||||
[](https://pkg.go.dev/github.com/duke-git/lancet/v2)
|
||||
[](https://goreportcard.com/report/github.com/duke-git/lancet/v2)
|
||||
[](https://github.com/duke-git/lancet/actions/workflows/codecov.yml)
|
||||
@@ -371,11 +371,11 @@ import "github.com/duke-git/lancet/v2/netutil"
|
||||
- [DecodeResponse](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#DecodeResponse)
|
||||
- [StructToUrlValues](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#StructToUrlValues)
|
||||
|
||||
- [HttpGet<sup>Deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpGet)
|
||||
- [HttpDelete<sup>Deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpDelete)
|
||||
- [HttpPost<sup>Deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPost)
|
||||
- [HttpPut<sup>Deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPut)
|
||||
- [HttpPatch<sup>Deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPatch)
|
||||
- [HttpGet<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpGet)
|
||||
- [HttpDelete<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpDelete)
|
||||
- [HttpPost<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPost)
|
||||
- [HttpPut<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPut)
|
||||
- [HttpPatch<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#HttpPatch)
|
||||
- [ParseHttpResponse](https://github.com/duke-git/lancet/blob/main/docs/netutil_zh-CN.md#ParseHttpResponse)
|
||||
|
||||
### 14. random 随机数生成器包,可以生成随机[]bytes, int, string。
|
||||
@@ -424,6 +424,7 @@ import "github.com/duke-git/lancet/v2/slice"
|
||||
- [Compact](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Compact)
|
||||
- [Concat](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Concat)
|
||||
- [Count](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Count)
|
||||
- [CountBy](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#CountBy)
|
||||
- [Difference](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Difference)
|
||||
- [DifferenceBy](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#DifferenceBy)
|
||||
- [DifferenceWith](https://github.com/duke-git/lancet/blob/main/docs/slice.md#DifferenceWith)
|
||||
@@ -438,21 +439,25 @@ import "github.com/duke-git/lancet/v2/slice"
|
||||
- [ForEach](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#ForEach)
|
||||
- [GroupBy](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#GroupBy)
|
||||
- [GroupWith](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#GroupWith)
|
||||
- [IntSlice](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#IntSlice)
|
||||
- [InterfaceSlice](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#InterfaceSlice)
|
||||
- [IntSlice<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#IntSlice)
|
||||
- [InterfaceSlice<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#InterfaceSlice)
|
||||
- [Intersection](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Intersection)
|
||||
- [InsertAt](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#InsertAt)
|
||||
- [IndexOf](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#IndexOf)
|
||||
- [LastIndexOf](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#LastIndexOf)
|
||||
- [Map](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Map)
|
||||
- [Merge](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Merge)
|
||||
- [Reverse](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Reverse)
|
||||
- [Reduce](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Reduce)
|
||||
- [Replace](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Replace)
|
||||
- [ReplaceAll](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#ReplaceAll)
|
||||
- [Repeat](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Repeat)
|
||||
- [Shuffle](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Shuffle)
|
||||
- [SortByField](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#SortByField)
|
||||
- [Sort](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Sort)
|
||||
- [SortBy](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#SortBy)
|
||||
- [SortByField<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#SortByField)
|
||||
- [Some](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#Some)
|
||||
- [StringSlice](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#StringSlice)
|
||||
- [StringSlice<sup>deprecated</sup>](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#StringSlice)
|
||||
- [SymmetricDifference](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#SymmetricDifference)
|
||||
- [ToSlice](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#ToSlice)
|
||||
- [ToSlicePointer](https://github.com/duke-git/lancet/blob/main/docs/slice_zh-CN.md#ToSlicePointer)
|
||||
|
||||
@@ -90,34 +90,50 @@ func ToChannel[T any](array []T) <-chan T {
|
||||
}
|
||||
|
||||
// ToString convert value to string
|
||||
// for number, string, []byte, will convert to string
|
||||
// for other type (slice, map, array, struct) will call json.Marshal
|
||||
func ToString(value any) string {
|
||||
result := ""
|
||||
if value == nil {
|
||||
return result
|
||||
return ""
|
||||
}
|
||||
|
||||
v := reflect.ValueOf(value)
|
||||
|
||||
switch value.(type) {
|
||||
case float32, float64:
|
||||
result = strconv.FormatFloat(v.Float(), 'f', -1, 64)
|
||||
return result
|
||||
case int, int8, int16, int32, int64:
|
||||
result = strconv.FormatInt(v.Int(), 10)
|
||||
return result
|
||||
case uint, uint8, uint16, uint32, uint64:
|
||||
result = strconv.FormatUint(v.Uint(), 10)
|
||||
return result
|
||||
case float32:
|
||||
return strconv.FormatFloat(float64(value.(float32)), 'f', -1, 32)
|
||||
case float64:
|
||||
return strconv.FormatFloat(value.(float64), 'f', -1, 64)
|
||||
case int:
|
||||
return strconv.FormatInt(int64(value.(int)), 10)
|
||||
case int8:
|
||||
return strconv.FormatInt(int64(value.(int8)), 10)
|
||||
case int16:
|
||||
return strconv.FormatInt(int64(value.(int16)), 10)
|
||||
case int32:
|
||||
return strconv.FormatInt(int64(value.(int32)), 10)
|
||||
case int64:
|
||||
return strconv.FormatInt(value.(int64), 10)
|
||||
case uint:
|
||||
return strconv.FormatUint(uint64(value.(uint)), 10)
|
||||
case uint8:
|
||||
return strconv.FormatUint(uint64(value.(uint8)), 10)
|
||||
case uint16:
|
||||
return strconv.FormatUint(uint64(value.(uint16)), 10)
|
||||
case uint32:
|
||||
return strconv.FormatUint(uint64(value.(uint32)), 10)
|
||||
case uint64:
|
||||
return strconv.FormatUint(value.(uint64), 10)
|
||||
case string:
|
||||
result = v.String()
|
||||
return result
|
||||
return value.(string)
|
||||
case []byte:
|
||||
result = string(v.Bytes())
|
||||
return result
|
||||
return string(value.([]byte))
|
||||
default:
|
||||
newValue, _ := json.Marshal(value)
|
||||
result = string(newValue)
|
||||
return result
|
||||
return string(newValue)
|
||||
|
||||
// todo: maybe we should't supprt other type conversion
|
||||
// v := reflect.ValueOf(value)
|
||||
// log.Panicf("Unsupported data type: %s ", v.String())
|
||||
// return ""
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -137,9 +137,10 @@ func TestToString(t *testing.T) {
|
||||
"", "",
|
||||
"0", "1", "-1",
|
||||
"123", "123", "123", "123", "123", "123", "123",
|
||||
"12.3", "12.300000190734863",
|
||||
"12.3", "12.3",
|
||||
"true", "false",
|
||||
"[1,2,3]", "{\"a\":1,\"b\":2,\"c\":3}", "{\"Name\":\"TestStruct\"}", "hello"}
|
||||
"[1,2,3]", "{\"a\":1,\"b\":2,\"c\":3}", "{\"Name\":\"TestStruct\"}", "hello",
|
||||
}
|
||||
|
||||
for i := 0; i < len(cases); i++ {
|
||||
actual := ToString(cases[i])
|
||||
|
||||
@@ -17,15 +17,19 @@ import (
|
||||
// AesEcbEncrypt encrypt data with key use AES ECB algorithm
|
||||
// len(key) should be 16, 24 or 32
|
||||
func AesEcbEncrypt(data, key []byte) []byte {
|
||||
cipher, _ := aes.NewCipher(generateAesKey(key))
|
||||
length := (len(data) + aes.BlockSize) / aes.BlockSize
|
||||
plain := make([]byte, length*aes.BlockSize)
|
||||
|
||||
copy(plain, data)
|
||||
|
||||
pad := byte(len(plain) - len(data))
|
||||
for i := len(data); i < len(plain); i++ {
|
||||
plain[i] = pad
|
||||
}
|
||||
|
||||
encrypted := make([]byte, len(plain))
|
||||
cipher, _ := aes.NewCipher(generateAesKey(key))
|
||||
|
||||
for bs, be := 0, cipher.BlockSize(); bs <= len(data); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
|
||||
cipher.Encrypt(encrypted[bs:be], plain[bs:be])
|
||||
}
|
||||
@@ -108,27 +112,32 @@ func AesCfbEncrypt(data, key []byte) []byte {
|
||||
|
||||
encrypted := make([]byte, aes.BlockSize+len(data))
|
||||
iv := encrypted[:aes.BlockSize]
|
||||
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
stream := cipher.NewCFBEncrypter(block, iv)
|
||||
stream.XORKeyStream(encrypted[aes.BlockSize:], data)
|
||||
|
||||
return encrypted
|
||||
}
|
||||
|
||||
// AesCfbDecrypt decrypt data with key use AES CFB algorithm
|
||||
// len(encrypted) should be great than 16, len(key) should be 16, 24 or 32
|
||||
func AesCfbDecrypt(encrypted, key []byte) []byte {
|
||||
block, _ := aes.NewCipher(key)
|
||||
if len(encrypted) < aes.BlockSize {
|
||||
panic("encrypted data is too short")
|
||||
}
|
||||
|
||||
block, _ := aes.NewCipher(key)
|
||||
iv := encrypted[:aes.BlockSize]
|
||||
encrypted = encrypted[aes.BlockSize:]
|
||||
|
||||
stream := cipher.NewCFBDecrypter(block, iv)
|
||||
|
||||
stream.XORKeyStream(encrypted, encrypted)
|
||||
|
||||
return encrypted
|
||||
}
|
||||
|
||||
@@ -139,6 +148,7 @@ func AesOfbEncrypt(data, key []byte) []byte {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
data = pkcs7Padding(data, aes.BlockSize)
|
||||
encrypted := make([]byte, aes.BlockSize+len(data))
|
||||
iv := encrypted[:aes.BlockSize]
|
||||
@@ -148,6 +158,7 @@ func AesOfbEncrypt(data, key []byte) []byte {
|
||||
|
||||
stream := cipher.NewOFB(block, iv)
|
||||
stream.XORKeyStream(encrypted[aes.BlockSize:], data)
|
||||
|
||||
return encrypted
|
||||
}
|
||||
|
||||
@@ -170,5 +181,6 @@ func AesOfbDecrypt(data, key []byte) []byte {
|
||||
mode.XORKeyStream(decrypted, data)
|
||||
|
||||
decrypted = pkcs7UnPadding(decrypted)
|
||||
|
||||
return decrypted
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
// DesEcbEncrypt encrypt data with key use DES ECB algorithm
|
||||
// len(key) should be 8
|
||||
func DesEcbEncrypt(data, key []byte) []byte {
|
||||
cipher, _ := des.NewCipher(generateDesKey(key))
|
||||
length := (len(data) + des.BlockSize) / des.BlockSize
|
||||
plain := make([]byte, length*des.BlockSize)
|
||||
copy(plain, data)
|
||||
@@ -26,6 +25,8 @@ func DesEcbEncrypt(data, key []byte) []byte {
|
||||
}
|
||||
|
||||
encrypted := make([]byte, len(plain))
|
||||
cipher, _ := des.NewCipher(generateDesKey(key))
|
||||
|
||||
for bs, be := 0, cipher.BlockSize(); bs <= len(data); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
|
||||
cipher.Encrypt(encrypted[bs:be], plain[bs:be])
|
||||
}
|
||||
@@ -59,6 +60,7 @@ func DesCbcEncrypt(data, key []byte) []byte {
|
||||
|
||||
encrypted := make([]byte, des.BlockSize+len(data))
|
||||
iv := encrypted[:des.BlockSize]
|
||||
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
@@ -4,22 +4,59 @@ package datastructure
|
||||
type Set[T comparable] map[T]struct{}
|
||||
|
||||
// NewSet return a instance of set
|
||||
func NewSet[T comparable](values ...T) Set[T] {
|
||||
func NewSet[T comparable](items ...T) Set[T] {
|
||||
set := make(Set[T])
|
||||
set.Add(values...)
|
||||
set.Add(items...)
|
||||
return set
|
||||
}
|
||||
|
||||
// Add value to set
|
||||
func (s Set[T]) Add(values ...T) {
|
||||
for _, v := range values {
|
||||
// NewSetFromSlice create a set from slice
|
||||
func NewSetFromSlice[T comparable](items []T) Set[T] {
|
||||
set := make(Set[T])
|
||||
for _, item := range items {
|
||||
set.Add(item)
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
// Add items to set
|
||||
func (s Set[T]) Add(items ...T) {
|
||||
for _, v := range items {
|
||||
s[v] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// Contain checks if set contains value or not
|
||||
func (s Set[T]) Contain(value T) bool {
|
||||
_, ok := s[value]
|
||||
// AddIfNotExist checks if item exists in the set,
|
||||
// it adds the item to set and returns true if it does not exist in the set,
|
||||
// or else it does nothing and returns false.
|
||||
func (s Set[T]) AddIfNotExist(item T) bool {
|
||||
if !s.Contain(item) {
|
||||
if _, ok := s[item]; !ok {
|
||||
s[item] = struct{}{}
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AddIfNotExistBy checks if item exists in the set and pass the `checker` function
|
||||
// it adds the item to set and returns true if it does not exists in the set and
|
||||
// function `checker` returns true, or else it does nothing and returns false.
|
||||
func (s Set[T]) AddIfNotExistBy(item T, checker func(element T) bool) bool {
|
||||
if !s.Contain(item) {
|
||||
if checker(item) {
|
||||
if _, ok := s[item]; !ok {
|
||||
s[item] = struct{}{}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Contain checks if set contains item or not
|
||||
func (s Set[T]) Contain(item T) bool {
|
||||
_, ok := s[item]
|
||||
return ok
|
||||
}
|
||||
|
||||
@@ -41,9 +78,9 @@ func (s Set[T]) Clone() Set[T] {
|
||||
return set
|
||||
}
|
||||
|
||||
// Delete value of set
|
||||
func (s Set[T]) Delete(values ...T) {
|
||||
for _, v := range values {
|
||||
// Delete item of set
|
||||
func (s Set[T]) Delete(items ...T) {
|
||||
for _, v := range items {
|
||||
delete(s, v)
|
||||
}
|
||||
}
|
||||
@@ -58,7 +95,7 @@ func (s Set[T]) Equal(other Set[T]) bool {
|
||||
}
|
||||
|
||||
// Iterate call function by every element of set
|
||||
func (s Set[T]) Iterate(fn func(value T)) {
|
||||
func (s Set[T]) Iterate(fn func(item T)) {
|
||||
for v := range s {
|
||||
fn(v)
|
||||
}
|
||||
@@ -76,13 +113,13 @@ func (s Set[T]) Size() int {
|
||||
|
||||
// Values return all values of set
|
||||
func (s Set[T]) Values() []T {
|
||||
values := make([]T, 0, 0)
|
||||
result := make([]T, 0, len(s))
|
||||
|
||||
s.Iterate(func(value T) {
|
||||
values = append(values, value)
|
||||
result = append(result, value)
|
||||
})
|
||||
|
||||
return values
|
||||
return result
|
||||
}
|
||||
|
||||
// Union creates a new set contain all element of set s and other
|
||||
|
||||
@@ -6,6 +6,19 @@ import (
|
||||
"github.com/duke-git/lancet/v2/internal"
|
||||
)
|
||||
|
||||
func TestSet_NewSetFromSlice(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSet_NewSetFromSlice")
|
||||
|
||||
s1 := NewSetFromSlice([]int{1, 2, 2, 3})
|
||||
assert.Equal(3, s1.Size())
|
||||
assert.Equal(true, s1.Contain(1))
|
||||
assert.Equal(true, s1.Contain(2))
|
||||
assert.Equal(true, s1.Contain(3))
|
||||
|
||||
s2 := NewSetFromSlice([]int{})
|
||||
assert.Equal(0, s2.Size())
|
||||
}
|
||||
|
||||
func TestSet_Add(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSet_Add")
|
||||
|
||||
@@ -17,6 +30,38 @@ func TestSet_Add(t *testing.T) {
|
||||
assert.Equal(true, set.Equal(expected))
|
||||
}
|
||||
|
||||
func TestSet_AddIfNotExist(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSet_AddIfNotExist")
|
||||
|
||||
set := NewSet[int]()
|
||||
set.Add(1, 2, 3)
|
||||
|
||||
assert.Equal(false, set.AddIfNotExist(1))
|
||||
assert.Equal(true, set.AddIfNotExist(4))
|
||||
assert.Equal(NewSet(1, 2, 3, 4), set)
|
||||
}
|
||||
|
||||
func TestSet_AddIfNotExistBy(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSet_AddIfNotExistBy")
|
||||
|
||||
set := NewSet[int]()
|
||||
set.Add(1, 2)
|
||||
|
||||
ok := set.AddIfNotExistBy(3, func(val int) bool {
|
||||
return val%2 != 0
|
||||
})
|
||||
|
||||
notOk := set.AddIfNotExistBy(4, func(val int) bool {
|
||||
return val%2 != 0
|
||||
})
|
||||
|
||||
assert.Equal(true, ok)
|
||||
assert.Equal(false, notOk)
|
||||
|
||||
assert.Equal(true, set.Contain(3))
|
||||
assert.Equal(false, set.Contain(4))
|
||||
}
|
||||
|
||||
func TestSet_Contain(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSet_Contain")
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
<div STYLE="page-break-after: always;"></div>
|
||||
|
||||
## Index
|
||||
|
||||
- [BubbleSort](#BubbleSort)
|
||||
- [InsertionSort](#InsertionSort)
|
||||
- [SelectionSort](#SelectionSort)
|
||||
@@ -31,7 +32,6 @@ import (
|
||||
- [CountSort](#CountSort)
|
||||
- [BinarySearch](#BinarySearch)
|
||||
- [BinaryIterativeSearch](#BinaryIterativeSearch)
|
||||
|
||||
- [LinearSearch](#LinearSearch)
|
||||
- [LRUCache](#LRUCache)
|
||||
|
||||
|
||||
@@ -29,7 +29,6 @@ import (
|
||||
- [QuickSort](#QuickSort)
|
||||
- [HeapSort](#HeapSort)
|
||||
- [MergeSort](#MergeSort)
|
||||
|
||||
- [CountSort](#CountSort)
|
||||
- [BinarySearch](#BinarySearch)
|
||||
- [BinaryIterativeSearch](#BinaryIterativeSearch)
|
||||
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
- [ToBytes](#ToBytes)
|
||||
- [ToChar](#ToChar)
|
||||
- [ToChannel](#ToChannel)
|
||||
|
||||
- [ToFloat](#ToFloat)
|
||||
- [ToInt](#ToInt)
|
||||
- [ToJson](#ToJson)
|
||||
@@ -395,6 +394,32 @@ func main() {
|
||||
```
|
||||
|
||||
|
||||
### <span id="ToString">ToString</span>
|
||||
|
||||
<p>ToString convert value to string, for number, string, []byte, will convert to string. For other type (slice, map, array, struct) will call json.Marshal</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func ToString(value any) string
|
||||
```
|
||||
<b>Example:</b>
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/convertor"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Printf("%q", convertor.ToString(1)) //"1"
|
||||
fmt.Printf("%q", convertor.ToString(1.1)) //"1.1"
|
||||
fmt.Printf("%q", convertor.ToString([]int{1, 2, 3})) //"[1,2,3]"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="StructToMap">StructToMap</span>
|
||||
|
||||
|
||||
@@ -27,7 +27,6 @@ import (
|
||||
- [ToBytes](#ToBytes)
|
||||
- [ToChar](#ToChar)
|
||||
- [ToChannel](#ToChannel)
|
||||
|
||||
- [ToFloat](#ToFloat)
|
||||
- [ToInt](#ToInt)
|
||||
- [ToJson](#ToJson)
|
||||
@@ -401,7 +400,7 @@ func main() {
|
||||
|
||||
### <span id="ToString">ToString</span>
|
||||
|
||||
<p>将interface转成字符串</p>
|
||||
<p>将值转换为字符串,对于数字、字符串、[]byte,将转换为字符串。 对于其他类型(切片、映射、数组、结构)将调用 json.Marshal</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
|
||||
@@ -47,7 +47,6 @@ import (
|
||||
- [HmacSha1](#HmacSha1)
|
||||
- [HmacSha256](#HmacSha256)
|
||||
- [HmacSha512](#HmacSha512)
|
||||
|
||||
- [Md5String](#Md5String)
|
||||
- [Md5File](#Md5File)
|
||||
- [Sha1](#Sha1)
|
||||
|
||||
@@ -33,7 +33,6 @@ import (
|
||||
- [AesOfbDecrypt](#AesOfbDecrypt)
|
||||
- [Base64StdEncode](#Base64StdEncode)
|
||||
- [Base64StdDecode](#Base64StdDecode)
|
||||
|
||||
- [DesEcbEncrypt](#DesEcbEncrypt)
|
||||
- [DesEcbDecrypt](#DesEcbDecrypt)
|
||||
- [DesCbcEncrypt](#DesCbcEncrypt)
|
||||
@@ -43,7 +42,6 @@ import (
|
||||
- [DesCfbDecrypt](#DesCfbDecrypt)
|
||||
- [DesOfbEncrypt](#DesOfbEncrypt)
|
||||
- [DesOfbDecrypt](#DesOfbDecrypt)
|
||||
|
||||
- [HmacMd5](#HmacMd5)
|
||||
- [HmacSha1](#HmacSha1)
|
||||
- [HmacSha256](#HmacSha256)
|
||||
|
||||
@@ -22,8 +22,11 @@ import (
|
||||
## Index
|
||||
|
||||
- [NewSet](#NewSet)
|
||||
- [NewSetFromSlice](#NewSetFromSlice)
|
||||
- [Values](#Values)
|
||||
- [Add](#Add)
|
||||
- [AddIfNotExist](#AddIfNotExist)
|
||||
- [AddIfNotExistBy](#AddIfNotExistBy)
|
||||
- [Delete](#Delete)
|
||||
- [Contain](#Contain)
|
||||
- [ContainAll](#ContainAll)
|
||||
@@ -34,7 +37,6 @@ import (
|
||||
- [IsEmpty](#IsEmpty)
|
||||
- [Union](#Union)
|
||||
- [Intersection](#Intersection)
|
||||
|
||||
- [SymmetricDifference](#SymmetricDifference)
|
||||
- [Minus](#Minus)
|
||||
|
||||
@@ -45,13 +47,13 @@ import (
|
||||
## Documentation
|
||||
|
||||
### <span id="NewSet">NewSet</span>
|
||||
<p>Make a Set instance</p>
|
||||
<p>Create a set instance</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
type Set[T comparable] map[T]bool
|
||||
func NewSet[T comparable](values ...T) Set[T]
|
||||
func NewSet[T comparable](items ...T) Set[T]
|
||||
```
|
||||
<b>Example:</b>
|
||||
|
||||
@@ -70,6 +72,30 @@ func main() {
|
||||
```
|
||||
|
||||
|
||||
### <span id="NewSetFromSlice">NewSetFromSlice</span>
|
||||
<p>Create a set from slice</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func NewSetFromSlice[T comparable](items []T) Set[T]
|
||||
```
|
||||
<b>Example:</b>
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
set "github.com/duke-git/lancet/v2/datastructure/set"
|
||||
)
|
||||
|
||||
func main() {
|
||||
st := set.NewSetFromSlice([]int{1, 2, 2, 3})
|
||||
fmt.Println(st.Values()) //1,2,3
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
### <span id="Values">Values</span>
|
||||
@@ -100,12 +126,12 @@ func main() {
|
||||
|
||||
|
||||
### <span id="Add">Add</span>
|
||||
<p>Add value to set</p>
|
||||
<p>Add items to set</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) Add(values ...T)
|
||||
func (s Set[T]) Add(items ...T)
|
||||
```
|
||||
<b>Example:</b>
|
||||
|
||||
@@ -126,14 +152,83 @@ func main() {
|
||||
```
|
||||
|
||||
|
||||
|
||||
### <span id="Delete">Delete</span>
|
||||
<p>Delete value in set</p>
|
||||
### <span id="AddIfNotExist">AddIfNotExist</span>
|
||||
<p>AddIfNotExist checks if item exists in the set, it adds the item to set and returns true if it does not exist in the set, or else it does nothing and returns false.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) Delete(values ...T)
|
||||
func (s Set[T]) AddIfNotExist(item T) bool
|
||||
```
|
||||
<b>Example:</b>
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
set "github.com/duke-git/lancet/v2/datastructure/set"
|
||||
)
|
||||
|
||||
func main() {
|
||||
st := set.NewSet[int]()
|
||||
st.Add(1, 2, 3)
|
||||
|
||||
r1 := st.AddIfNotExist(1)
|
||||
r2 := st.AddIfNotExist(4)
|
||||
|
||||
fmt.Println(r1) // false
|
||||
fmt.Println(r2) // true
|
||||
fmt.Println(st.Values()) // 1,2,3,4
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="AddIfNotExistBy">AddIfNotExistBy</span>
|
||||
<p>AddIfNotExistBy checks if item exists in the set and pass the `checker` function it adds the item to set and returns true if it does not exists in the set and function `checker` returns true, or else it does nothing and returns false.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) AddIfNotExistBy(item T, checker func(element T) bool) bool
|
||||
```
|
||||
<b>Example:</b>
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
set "github.com/duke-git/lancet/v2/datastructure/set"
|
||||
)
|
||||
|
||||
func main() {
|
||||
st := set.NewSet[int]()
|
||||
st.Add(1, 2)
|
||||
|
||||
ok := st.AddIfNotExistBy(3, func(val int) bool {
|
||||
return val%2 != 0
|
||||
})
|
||||
fmt.Println(ok) // true
|
||||
|
||||
|
||||
notOk := st.AddIfNotExistBy(4, func(val int) bool {
|
||||
return val%2 != 0
|
||||
})
|
||||
fmt.Println(notOk) // false
|
||||
|
||||
fmt.Println(st.Values()) // 1, 2, 3
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="Delete">Delete</span>
|
||||
<p>Delete item in set</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) Delete(items ...T)
|
||||
```
|
||||
<b>Example:</b>
|
||||
|
||||
@@ -157,12 +252,12 @@ func main() {
|
||||
|
||||
|
||||
### <span id="Contain">Contain</span>
|
||||
<p>Check if value is in set or not</p>
|
||||
<p>Check if item is in set or not</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) Contain(value T) bool
|
||||
func (s Set[T]) Contain(item T) bool
|
||||
```
|
||||
<b>Example:</b>
|
||||
|
||||
@@ -309,7 +404,7 @@ func main() {
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) Iterate(fn func(value T))
|
||||
func (s Set[T]) Iterate(fn func(item T))
|
||||
```
|
||||
<b>Example:</b>
|
||||
|
||||
@@ -324,8 +419,8 @@ import (
|
||||
func main() {
|
||||
set1 := set.NewSet(1, 2, 3)
|
||||
arr := []int{}
|
||||
set.Iterate(func(value int) {
|
||||
arr = append(arr, value)
|
||||
set.Iterate(func(item int) {
|
||||
arr = append(arr, item)
|
||||
})
|
||||
|
||||
fmt.Println(arr) //1,2,3
|
||||
|
||||
@@ -22,8 +22,11 @@ import (
|
||||
## 目录
|
||||
|
||||
- [NewSet](#NewSet)
|
||||
- [NewSetFromSlice](#NewSetFromSlice)
|
||||
- [Values](#Values)
|
||||
- [Add](#Add)
|
||||
- [AddIfNotExist](#AddIfNotExist)
|
||||
- [AddIfNotExistBy](#AddIfNotExistBy)
|
||||
- [Delete](#Delete)
|
||||
- [Contain](#Contain)
|
||||
- [ContainAll](#ContainAll)
|
||||
@@ -34,7 +37,6 @@ import (
|
||||
- [IsEmpty](#IsEmpty)
|
||||
- [Union](#Union)
|
||||
- [Intersection](#Intersection)
|
||||
|
||||
- [SymmetricDifference](#SymmetricDifference)
|
||||
- [Minus](#Minus)
|
||||
|
||||
@@ -51,7 +53,7 @@ import (
|
||||
|
||||
```go
|
||||
type Set[T comparable] map[T]bool
|
||||
func NewSet[T comparable](values ...T) Set[T]
|
||||
func NewSet[T comparable](items ...T) Set[T]
|
||||
```
|
||||
<b>例子:</b>
|
||||
|
||||
@@ -71,6 +73,31 @@ func main() {
|
||||
|
||||
|
||||
|
||||
### <span id="NewSetFromSlice">NewSetFromSlice</span>
|
||||
<p>基于切片创建集合</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func NewSetFromSlice[T comparable](items []T) Set[T]
|
||||
```
|
||||
<b>例子:</b>
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
set "github.com/duke-git/lancet/v2/datastructure/set"
|
||||
)
|
||||
|
||||
func main() {
|
||||
st := set.NewSetFromSlice([]int{1, 2, 2, 3})
|
||||
fmt.Println(st.Values()) //1,2,3
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
### <span id="Values">Values</span>
|
||||
<p>获取集合中所有元素的切片</p>
|
||||
@@ -105,7 +132,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) Add(values ...T)
|
||||
func (s Set[T]) Add(items ...T)
|
||||
```
|
||||
<b>例子:</b>
|
||||
|
||||
@@ -126,6 +153,76 @@ func main() {
|
||||
```
|
||||
|
||||
|
||||
### <span id="AddIfNotExist">AddIfNotExist</span>
|
||||
<p>如果集合中不存在元素,则添加该元素返回true, 如果集合中存在元素, 不做任何操作,返回false</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) AddIfNotExist(item T) bool
|
||||
```
|
||||
<b>例子:</b>
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
set "github.com/duke-git/lancet/v2/datastructure/set"
|
||||
)
|
||||
|
||||
func main() {
|
||||
st := set.NewSet[int]()
|
||||
st.Add(1, 2, 3)
|
||||
|
||||
r1 := st.AddIfNotExist(1)
|
||||
r2 := st.AddIfNotExist(4)
|
||||
|
||||
fmt.Println(r1) // false
|
||||
fmt.Println(r2) // true
|
||||
fmt.Println(st.Values()) // 1,2,3,4
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="AddIfNotExistBy">AddIfNotExistBy</span>
|
||||
<p>根据checker函数判断元素是否在集合中,如果集合中不存在元素且checker返回true,则添加该元素返回true, 否则不做任何操作,返回false</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) AddIfNotExistBy(item T, checker func(element T) bool) bool
|
||||
```
|
||||
<b>例子:</b>
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
set "github.com/duke-git/lancet/v2/datastructure/set"
|
||||
)
|
||||
|
||||
func main() {
|
||||
st := set.NewSet[int]()
|
||||
st.Add(1, 2)
|
||||
|
||||
ok := st.AddIfNotExistBy(3, func(val int) bool {
|
||||
return val%2 != 0
|
||||
})
|
||||
fmt.Println(ok) // true
|
||||
|
||||
|
||||
notOk := st.AddIfNotExistBy(4, func(val int) bool {
|
||||
return val%2 != 0
|
||||
})
|
||||
fmt.Println(notOk) // false
|
||||
|
||||
fmt.Println(st.Values()) // 1, 2, 3
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
### <span id="Delete">Delete</span>
|
||||
<p>删除集合中元素</p>
|
||||
@@ -133,7 +230,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) Delete(values ...T)
|
||||
func (s Set[T]) Delete(items ...T)
|
||||
```
|
||||
<b>例子:</b>
|
||||
|
||||
@@ -162,7 +259,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) Contain(value T) bool
|
||||
func (s Set[T]) Contain(item T) bool
|
||||
```
|
||||
<b>例子:</b>
|
||||
|
||||
@@ -309,7 +406,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func (s Set[T]) Iterate(fn func(value T))
|
||||
func (s Set[T]) Iterate(fn func(item T))
|
||||
```
|
||||
<b>例子:</b>
|
||||
|
||||
@@ -324,8 +421,8 @@ import (
|
||||
func main() {
|
||||
set1 := set.NewSet(1, 2, 3)
|
||||
arr := []int{}
|
||||
set.Iterate(func(value int) {
|
||||
arr = append(arr, value)
|
||||
set.Iterate(func(item int) {
|
||||
arr = append(arr, item)
|
||||
})
|
||||
|
||||
fmt.Println(arr) //1,2,3
|
||||
@@ -420,9 +517,6 @@ func main() {
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
### <span id="SymmetricDifference">SymmetricDifference</span>
|
||||
<p>返回一个集合,其中元素在第一个集合或第二个集合中,且不同时存在于两个集合中</p>
|
||||
|
||||
|
||||
@@ -29,7 +29,6 @@ import (
|
||||
- [PreOrderTraverse](#BSTree_PreOrderTraverse)
|
||||
- [InOrderTraverse](#BSTree_InOrderTraverse)
|
||||
- [PostOrderTraverse](#BSTree_PostOrderTraverse)
|
||||
|
||||
- [LevelOrderTraverse](#BSTree_LevelOrderTraverse)
|
||||
- [Depth](#BSTree_Depth)
|
||||
- [HasSubTree](#BSTree_HasSubTree)
|
||||
|
||||
@@ -29,7 +29,6 @@ import (
|
||||
- [PreOrderTraverse](#BSTree_PreOrderTraverse)
|
||||
- [InOrderTraverse](#BSTree_InOrderTraverse)
|
||||
- [PostOrderTraverse](#BSTree_PostOrderTraverse)
|
||||
|
||||
- [LevelOrderTraverse](#BSTree_LevelOrderTraverse)
|
||||
- [Depth](#BSTree_Depth)
|
||||
- [HasSubTree](#BSTree_HasSubTree)
|
||||
|
||||
@@ -42,7 +42,6 @@ import (
|
||||
- [GetNightTimestamp](#GetNightTimestamp)
|
||||
- [FormatTimeToStr](#FormatTimeToStr)
|
||||
- [FormatStrToTime](#FormatStrToTime)
|
||||
|
||||
- [NewUnixNow](#NewUnixNow)
|
||||
- [NewUnix](#NewUnix)
|
||||
- [NewFormat](#NewFormat)
|
||||
|
||||
@@ -41,7 +41,6 @@ import (
|
||||
- [GetNightTimestamp](#GetNightTimestamp)
|
||||
- [FormatTimeToStr](#FormatTimeToStr)
|
||||
- [FormatStrToTime](#FormatStrToTime)
|
||||
|
||||
- [NewUnixNow](#NewUnixNow)
|
||||
- [NewUnix](#NewUnix)
|
||||
- [NewFormat](#NewFormat)
|
||||
|
||||
@@ -28,7 +28,6 @@ import (
|
||||
- [IsExist](#IsExist)
|
||||
- [IsLink](#IsLink)
|
||||
- [IsDir](#IsDir)
|
||||
|
||||
- [ListFileNames](#ListFileNames)
|
||||
- [RemoveFile](#RemoveFile)
|
||||
- [ReadFileToString](#ReadFileToString)
|
||||
|
||||
@@ -28,7 +28,6 @@ import (
|
||||
- [IsExist](#IsExist)
|
||||
- [IsLink](#IsLink)
|
||||
- [IsDir](#IsDir)
|
||||
|
||||
- [ListFileNames](#ListFileNames)
|
||||
- [RemoveFile](#RemoveFile)
|
||||
- [ReadFileToString](#ReadFileToString)
|
||||
|
||||
@@ -28,7 +28,6 @@ import (
|
||||
- [MaxBy](#MaxBy)
|
||||
- [Min](#Min)
|
||||
- [MinBy](#MaxBy)
|
||||
|
||||
- [Percent](#Percent)
|
||||
- [RoundToFloat](#RoundToFloat)
|
||||
- [RoundToString](#RoundToString)
|
||||
|
||||
@@ -28,7 +28,6 @@ import (
|
||||
- [MaxBy](#MaxBy)
|
||||
- [Min](#Min)
|
||||
- [MinBy](#MaxBy)
|
||||
|
||||
- [Percent](#Percent)
|
||||
- [RoundToFloat](#RoundToFloat)
|
||||
- [RoundToString](#RoundToString)
|
||||
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
## Index
|
||||
- [ConvertMapToQueryString](#ConvertMapToQueryString)
|
||||
- [EncodeUrl](#EncodeUrl)
|
||||
|
||||
- [GetInternalIp](#GetInternalIp)
|
||||
- [GetIps](#GetIps)
|
||||
- [GetMacAddrs](#GetMacAddrs)
|
||||
@@ -38,7 +37,6 @@ import (
|
||||
- [SendRequest](#SendRequest)
|
||||
- [DecodeResponse](#DecodeResponse)
|
||||
- [StructToUrlValues](#StructToUrlValues)
|
||||
|
||||
- [HttpGet<sup>Deprecated</sup>](#HttpGet)
|
||||
- [HttpDelete<sup>Deprecated</sup>](#HttpDelete)
|
||||
- [HttpPost<sup>Deprecated</sup>](#HttpPost)
|
||||
|
||||
@@ -30,7 +30,6 @@ import (
|
||||
- [GetMacAddrs](#GetMacAddrs)
|
||||
- [GetPublicIpInfo](#GetPublicIpInfo)
|
||||
- [GetRequestPublicIp](#GetRequestPublicIp)
|
||||
|
||||
- [IsPublicIP](#IsPublicIP)
|
||||
- [IsInternalIP](#IsInternalIP)
|
||||
- [HttpRequest](#HttpRequest)
|
||||
@@ -38,13 +37,11 @@ import (
|
||||
- [SendRequest](#SendRequest)
|
||||
- [DecodeResponse](#DecodeResponse)
|
||||
- [StructToUrlValues](#StructToUrlValues)
|
||||
|
||||
- [HttpGet<sup>Deprecated</sup>](#HttpGet)
|
||||
- [HttpDelete<sup>Deprecated</sup>](#HttpDelete)
|
||||
- [HttpPost<sup>Deprecated</sup>](#HttpPost)
|
||||
- [HttpPut<sup>Deprecated</sup>](#HttpPut)
|
||||
- [HttpPatch<sup>Deprecated</sup>](#HttpPatch)
|
||||
|
||||
- [ParseHttpResponse](#ParseHttpResponse)
|
||||
|
||||
<div STYLE="page-break-after: always;"></div>
|
||||
|
||||
@@ -26,7 +26,6 @@ import (
|
||||
- [RandInt](#RandInt)
|
||||
- [RandString](#RandString)
|
||||
- [RandUpper](#RandUpper)
|
||||
|
||||
- [RandLower](#RandLower)
|
||||
- [RandNumeral](#RandNumeral)
|
||||
- [RandNumeralOrLetter](#RandNumeralOrLetter)
|
||||
|
||||
@@ -26,7 +26,6 @@ import (
|
||||
- [RandInt](#RandInt)
|
||||
- [RandString](#RandString)
|
||||
- [RandUpper](#RandUpper)
|
||||
|
||||
- [RandLower](#RandLower)
|
||||
- [RandNumeral](#RandNumeral)
|
||||
- [RandNumeralOrLetter](#RandNumeralOrLetter)
|
||||
|
||||
238
docs/slice.md
238
docs/slice.md
@@ -29,6 +29,7 @@ import (
|
||||
- [Compact](#Compact)
|
||||
- [Concat](#Concat)
|
||||
- [Count](#Count)
|
||||
- [CountBy](#CountBy)
|
||||
- [Difference](#Difference)
|
||||
- [DifferenceBy](#DifferenceBy)
|
||||
- [DifferenceWith](#DifferenceWith)
|
||||
@@ -43,24 +44,27 @@ import (
|
||||
- [Flatten](#Flatten)
|
||||
- [FlattenDeep](#FlattenDeep)
|
||||
- [ForEach](#ForEach)
|
||||
|
||||
- [GroupBy](#GroupBy)
|
||||
- [GroupWith](#GroupWith)
|
||||
- [IntSlice](#IntSlice)
|
||||
- [InterfaceSlice](#InterfaceSlice)
|
||||
- [IntSlice<sup>deprecated</sup>](#IntSlice)
|
||||
- [InterfaceSlice<sup>deprecated</sup>](#InterfaceSlice)
|
||||
- [Intersection](#Intersection)
|
||||
- [InsertAt](#InsertAt)
|
||||
- [IndexOf](#IndexOf)
|
||||
- [LastIndexOf](#LastIndexOf)
|
||||
- [Map](#Map)
|
||||
- [Merge](#Merge)
|
||||
- [Reverse](#Reverse)
|
||||
- [Reduce](#Reduce)
|
||||
- [Replace](#Replace)
|
||||
- [ReplaceAll](#ReplaceAll)
|
||||
- [Repeat](#Repeat)
|
||||
- [Shuffle](#Shuffle)
|
||||
- [SortByField](#SortByField)
|
||||
- [Sort](#Sort)
|
||||
- [SortBy](#SortBy)
|
||||
- [SortByField<sup>deprecated</sup>](#SortByField)
|
||||
- [Some](#Some)
|
||||
- [StringSlice](#StringSlice)
|
||||
- [StringSlice<sup>deprecated</sup>](#StringSlice)
|
||||
- [SymmetricDifference](#SymmetricDifference)
|
||||
- [ToSlice](#ToSlice)
|
||||
- [ToSlicePointer](#ToSlicePointer)
|
||||
@@ -78,12 +82,12 @@ import (
|
||||
|
||||
### <span id="AppendIfAbsent">AppendIfAbsent</span>
|
||||
|
||||
<p>If slice doesn't contain the value, append it to the slice.</p>
|
||||
<p>If slice doesn't contain the item, append it to the slice.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func AppendIfAbsent[T comparable](slice []T, value T) []T
|
||||
func AppendIfAbsent[T comparable](slice []T, item T) []T
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
@@ -106,12 +110,12 @@ func main() {
|
||||
|
||||
### <span id="Contain">Contain</span>
|
||||
|
||||
<p>Check if the value is in the slice or not.</p>
|
||||
<p>Check if the target value is in the slice or not.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func Contain[T comparable](slice []T, value T) bool
|
||||
func Contain[T comparable](slice []T, target T) bool
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
@@ -135,7 +139,7 @@ func main() {
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func ContainSubSlice[T comparable](slice, subslice []T) bool
|
||||
func ContainSubSlice[T comparable](slice, subSlice []T) bool
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
@@ -172,8 +176,8 @@ import (
|
||||
|
||||
func main() {
|
||||
arr := []string{"a", "b", "c", "d", "e"}
|
||||
res := slice.Chunk(InterfaceSlice(arr), 3)
|
||||
fmt.Println(res) //[][]any{{"a", "b", "c"}, {"d", "e"}}
|
||||
res := slice.Chunk((arr), 3)
|
||||
fmt.Println(res) //[][]string{{"a", "b", "c"}, {"d", "e"}}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -184,7 +188,7 @@ func main() {
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func Compact[T any](slice []T) []T
|
||||
func Compact[T comparable](slice []T) []T
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
@@ -203,12 +207,12 @@ func main() {
|
||||
|
||||
### <span id="Concat">Concat</span>
|
||||
|
||||
<p>Creates a new slice concatenating slice with any additional slices and/or values.</p>
|
||||
<p>Creates a new slice concatenating slice with any additional slices.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func Concat[T any](slice []T, values ...[]T) []T
|
||||
func Concat[T any](slice []T, slices ...[]T) []T
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
@@ -230,12 +234,38 @@ func main() {
|
||||
|
||||
### <span id="Count">Count</span>
|
||||
|
||||
<p>Count iterates over elements of slice, returns a count of all matched elements.</p>
|
||||
<p>Returns the number of occurrences of the given item in the slice.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func Count[T any](slice []T, predicate func(index int, t T) bool) int
|
||||
func Count[T comparable](slice []T, item T) int
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/slice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
nums := []int{1, 2, 3, 3, 4, 5}
|
||||
|
||||
fmt.Println(slice.Count(nums, 1)) //1
|
||||
fmt.Println(slice.Count(nums, 3)) //2
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="CountBy">CountBy</span>
|
||||
|
||||
<p>Iterates over elements of slice with predicate function, returns the number of all matched elements.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func CountBy[T any](slice []T, predicate func(index int, item T) bool) int
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
@@ -248,15 +278,16 @@ import (
|
||||
|
||||
func main() {
|
||||
nums := []int{1, 2, 3, 4, 5, 6}
|
||||
evenFunc := func(i, num int) bool {
|
||||
evenFunc := func(_, num int) bool {
|
||||
return (num % 2) == 0
|
||||
}
|
||||
|
||||
res := slice.Count(nums, evenFunc)
|
||||
res := slice.CountBy(nums, evenFunc)
|
||||
fmt.Println(res) //3
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="Difference">Difference</span>
|
||||
|
||||
<p>Creates an slice of whose element not included in the other given slice.</p>
|
||||
@@ -715,11 +746,12 @@ func main() {
|
||||
return math.Floor(num)
|
||||
}
|
||||
res := slice.GroupWith(nums, floor)
|
||||
|
||||
fmt.Println(res) //map[float64][]float64{ 4: {4.2}, 6: {6.1, 6.3},}
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="IntSlice">IntSlice</span>
|
||||
### <span id="IntSlice">IntSlice (Deprecated: use generic feature of go1.18+ for replacement)</span>
|
||||
|
||||
<p>Convert interface slice to int slice.</p>
|
||||
|
||||
@@ -744,7 +776,7 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="InterfaceSlice">InterfaceSlice</span>
|
||||
### <span id="InterfaceSlice">InterfaceSlice (Deprecated: use generic feature of go1.18+ for replacement)</span>
|
||||
|
||||
<p>Convert value to interface slice.</p>
|
||||
|
||||
@@ -827,12 +859,12 @@ func main() {
|
||||
|
||||
### <span id="IndexOf">IndexOf</span>
|
||||
|
||||
<p>Returns the index at which the first occurrence of a value is found in a slice or return -1 if the value cannot be found.</p>
|
||||
<p>Returns the index at which the first occurrence of a item is found in a slice or return -1 if the item cannot be found.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func IndexOf[T comparable](slice []T, value T) int
|
||||
func IndexOf[T comparable](slice []T, item T) int
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
@@ -855,12 +887,12 @@ func main() {
|
||||
|
||||
### <span id="LastIndexOf">LastIndexOf</span>
|
||||
|
||||
<p>Returns the index at which the last occurrence of a value is found in a slice or return -1 if the value cannot be found.</p>
|
||||
<p>Returns the index at which the last occurrence of a item is found in a slice or return -1 if the item cannot be found.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func LastIndexOf[T comparable](slice []T, value T) int
|
||||
func LastIndexOf[T comparable](slice []T, item T) int
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
@@ -909,6 +941,36 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="Merge">Merge</span>
|
||||
|
||||
<p>Merge all given slices into one slice.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func Merge[T any](slices ...[]T) []T
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/slice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
s1 := []int{1, 2, 3}
|
||||
s2 := []int{2, 4}
|
||||
res := slice.Merge(s1, s2)
|
||||
|
||||
fmt.Println(res) //[]int{1, 2, 3, 2, 4}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
### <span id="Reverse">Reverse</span>
|
||||
|
||||
<p>Reverse the elements order in slice.</p>
|
||||
@@ -1018,6 +1080,31 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="Repeat">Repeat</span>
|
||||
|
||||
<p>Creates a slice with length n whose elements are passed param item.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func Repeat[T any](item T, n int) []T
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/slice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println(slice.Repeat("a", 3)) //[]string{"a", "a", "a"}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="Shuffle">Shuffle</span>
|
||||
|
||||
<p>Creates an slice of shuffled values.</p>
|
||||
@@ -1043,7 +1130,94 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="SortByField">SortByField</span>
|
||||
### <span id="Sort">Sort</span>
|
||||
|
||||
<p>Sorts a slice of any ordered type(number or string), use quick sort algrithm. Default sort order is ascending (asc), if want descending order, set param `sortOrder` to `desc`. Ordered type: number(all ints uints floats) or string.
|
||||
</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func Sort[T lancetconstraints.Ordered](slice []T, sortOrder ...string)
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/slice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
numbers := []int{1, 4, 3, 2, 5}
|
||||
|
||||
slice.Sort(numbers)
|
||||
fmt.Println(numbers) //{1,2,3,4,5}
|
||||
|
||||
slice.Sort(numbers, "desc")
|
||||
fmt.Println(numbers) //{5,4,3,2,1}
|
||||
|
||||
strings := []string{"a", "d", "c", "b", "e"}
|
||||
|
||||
slice.Sort(strings)
|
||||
fmt.Println(strings) //{"a", "b", "c", "d", "e"}
|
||||
|
||||
slice.Sort(strings, "desc")
|
||||
fmt.Println(strings) //{"e", "d", "c", "b", "a"}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="SortBy">SortBy</span>
|
||||
|
||||
<p>Sorts the slice in ascending order as determined by the less function. This sort is not guaranteed to be stable.<p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func SortBy[T any](slice []T, less func(a, b T) bool)
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/slice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
numbers := []int{1, 4, 3, 2, 5}
|
||||
|
||||
slice.SortBy(numbers, func(a, b int) bool {
|
||||
return a < b
|
||||
})
|
||||
fmt.Println(numbers) //{1, 2, 3, 4, 5}
|
||||
|
||||
type User struct {
|
||||
Name string
|
||||
Age uint
|
||||
}
|
||||
|
||||
users := []User{
|
||||
{Name: "a", Age: 21},
|
||||
{Name: "b", Age: 15},
|
||||
{Name: "c", Age: 100}}
|
||||
|
||||
slice.SortBy(users, func(a, b User) bool {
|
||||
return a.Age < b.Age
|
||||
})
|
||||
|
||||
fmt.Printf("sort users by age: %v", users)
|
||||
|
||||
// output
|
||||
// [{b 15} {a 21} {c 100}]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="SortByField">SortByField (Deprecated: use Sort and SortBy for replacement)</span>
|
||||
|
||||
<p>Sort struct slice by field. Slice element should be struct, field type should be int, uint, string, or bool. Default sort type is ascending (asc), if descending order, set sortType to desc</p>
|
||||
|
||||
@@ -1115,7 +1289,7 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="StringSlice">StringSlice</span>
|
||||
### <span id="StringSlice">StringSlice (Deprecated: use generic feature of go1.18+ for replacement)</span>
|
||||
|
||||
<p>Convert interface slice to string slice.</p>
|
||||
|
||||
@@ -1171,12 +1345,12 @@ func main() {
|
||||
|
||||
### <span id="ToSlice">ToSlice</span>
|
||||
|
||||
<p>Returns a slices of a variable parameter transformation</p>
|
||||
<p>Creates a slice of give items.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func ToSlice[T any](value ...T) []T
|
||||
func ToSlice[T any](items ...T) []T
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
@@ -1200,7 +1374,7 @@ func main() {
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func ToSlicePointer[T any](value ...T) []*T
|
||||
func ToSlicePointer[T any](items ...T) []*T
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
@@ -1351,12 +1525,12 @@ func main() {
|
||||
|
||||
### <span id="Without">Without</span>
|
||||
|
||||
<p>Creates a slice excluding all given values. </p>
|
||||
<p>Creates a slice excluding all given items. </p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func Without[T comparable](slice []T, values ...T) []T
|
||||
func Without[T comparable](slice []T, items ...T) []T
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
|
||||
@@ -20,8 +20,10 @@ import (
|
||||
|
||||
<div STYLE="page-break-after: always;"></div>
|
||||
|
||||
|
||||
## 目录
|
||||
|
||||
|
||||
- [AppendIfAbsent](#AppendIfAbsent)
|
||||
- [Contain](#Contain)
|
||||
- [ContainSubSlice](#ContainSubSlice)
|
||||
@@ -29,6 +31,7 @@ import (
|
||||
- [Compact](#Compact)
|
||||
- [Concat](#Concat)
|
||||
- [Count](#Count)
|
||||
- [CountBy](#CountBy)
|
||||
- [Difference](#Difference)
|
||||
- [DifferenceBy](#DifferenceBy)
|
||||
- [DifferenceWith](#DifferenceWith)
|
||||
@@ -45,22 +48,25 @@ import (
|
||||
- [ForEach](#ForEach)
|
||||
- [GroupBy](#GroupBy)
|
||||
- [GroupWith](#GroupWith)
|
||||
- [IntSlice](#IntSlice)
|
||||
|
||||
- [InterfaceSlice](#InterfaceSlice)
|
||||
- [IntSlice<sup>deprecated</sup>](#IntSlice)
|
||||
- [InterfaceSlice<sup>deprecated</sup>](#InterfaceSlice)
|
||||
- [Intersection](#Intersection)
|
||||
- [InsertAt](#InsertAt)
|
||||
- [IndexOf](#IndexOf)
|
||||
- [LastIndexOf](#LastIndexOf)
|
||||
- [Map](#Map)
|
||||
- [Merge](#Merge)
|
||||
- [Reverse](#Reverse)
|
||||
- [Reduce](#Reduce)
|
||||
- [Replace](#Replace)
|
||||
- [ReplaceAll](#ReplaceAll)
|
||||
- [Repeat](#Repeat)
|
||||
- [Shuffle](#Shuffle)
|
||||
- [SortByField](#SortByField)
|
||||
- [Sort](#Sort)
|
||||
- [SortBy](#SortBy)
|
||||
- [SortByField<sup>deprecated</sup>](#SortByField)
|
||||
- [Some](#Some)
|
||||
- [StringSlice](#StringSlice)
|
||||
- [StringSlice<sup>deprecated</sup>](#StringSlice)
|
||||
- [SymmetricDifference](#SymmetricDifference)
|
||||
- [ToSlice](#ToSlice)
|
||||
- [ToSlicePointer](#ToSlicePointer)
|
||||
@@ -72,6 +78,7 @@ import (
|
||||
- [Without](#Without)
|
||||
- [KeyBy](#KeyBy)
|
||||
|
||||
|
||||
<div STYLE="page-break-after: always;"></div>
|
||||
|
||||
## 文档
|
||||
@@ -83,7 +90,7 @@ import (
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func AppendIfAbsent[T comparable](slice []T, value T) []T
|
||||
func AppendIfAbsent[T comparable](slice []T, item T) []T
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
@@ -111,7 +118,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func Contain[T comparable](slice []T, value T) bool
|
||||
func Contain[T comparable](slice []T, target T) bool
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
@@ -135,7 +142,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func ContainSubSlice[T comparable](slice, subslice []T) bool
|
||||
func ContainSubSlice[T comparable](slice, subSlice []T) bool
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
@@ -172,8 +179,8 @@ import (
|
||||
|
||||
func main() {
|
||||
arr := []string{"a", "b", "c", "d", "e"}
|
||||
res := slice.Chunk(InterfaceSlice(arr), 3)
|
||||
fmt.Println(res) //[][]any{{"a", "b", "c"}, {"d", "e"}}
|
||||
res := slice.Chunk(arr, 3)
|
||||
fmt.Println(res) //[][]string{{"a", "b", "c"}, {"d", "e"}}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -184,7 +191,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func Compact[T any](slice []T) []T
|
||||
func Compact[T comparable](slice []T) []T
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
@@ -203,12 +210,12 @@ func main() {
|
||||
|
||||
### <span id="Concat">Concat</span>
|
||||
|
||||
<p>连接values到slice中,values类型可以是切片或多个值</p>
|
||||
<p>合并多个slices到slice中</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func Concat[T any](slice []T, values ...[]T) []T
|
||||
func Concat[T any](slice []T, slices ...[]T) []T
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
@@ -230,12 +237,38 @@ func main() {
|
||||
|
||||
### <span id="Count">Count</span>
|
||||
|
||||
<p>遍历切片,对每个元素执行函数function. 返回符合函数返回值为true的元素的个数</p>
|
||||
<p>返回切片中指定元素的个数</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func Count[T any](slice []T, predicate func(index int, t T) bool) int
|
||||
func Count[T comparable](slice []T, item T) int
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/slice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
nums := []int{1, 2, 3, 3, 4, 5}
|
||||
|
||||
fmt.Println(slice.Count(nums, 1)) //1
|
||||
fmt.Println(slice.Count(nums, 3)) //2
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="CountBy">CountBy</span>
|
||||
|
||||
<p>遍历切片,对每个元素执行函数predicate. 返回符合函数返回值为true的元素的个数.</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func CountBy[T any](slice []T, predicate func(index int, item T) bool) int
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
@@ -248,11 +281,11 @@ import (
|
||||
|
||||
func main() {
|
||||
nums := []int{1, 2, 3, 4, 5, 6}
|
||||
evenFunc := func(i, num int) bool {
|
||||
evenFunc := func(_, num int) bool {
|
||||
return (num % 2) == 0
|
||||
}
|
||||
|
||||
res := slice.Count(nums, evenFunc)
|
||||
res := slice.CountBy(nums, evenFunc)
|
||||
fmt.Println(res) //3
|
||||
}
|
||||
```
|
||||
@@ -719,7 +752,7 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="IntSlice">IntSlice</span>
|
||||
### <span id="IntSlice">IntSlice (已弃用: 使用go1.18+泛型代替)</span>
|
||||
|
||||
<p>将接口切片转换为int切片</p>
|
||||
|
||||
@@ -744,7 +777,7 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="InterfaceSlice">InterfaceSlice</span>
|
||||
### <span id="InterfaceSlice">InterfaceSlice(已弃用: 使用go1.18+泛型代替)</span>
|
||||
|
||||
<p>将值转换为接口切片</p>
|
||||
|
||||
@@ -832,7 +865,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func IndexOf[T comparable](slice []T, value T) int
|
||||
func IndexOf[T comparable](slice []T, item T) int
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
@@ -860,7 +893,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func LastIndexOf[T comparable](slice []T, value T) int
|
||||
func LastIndexOf[T comparable](slice []T, item T) int
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
@@ -883,7 +916,7 @@ func main() {
|
||||
|
||||
### <span id="Map">Map</span>
|
||||
|
||||
<p>通过运行函数slice中的每个元素来创建一个新切片</p>
|
||||
<p>对slice中的每个元素执行map函数以创建一个新切片</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
@@ -909,6 +942,34 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="Merge">Merge</span>
|
||||
|
||||
<p>合并多个切片(不会消除重复元素).</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func Merge[T any](slices ...[]T) []T
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/slice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
s1 := []int{1, 2, 3}
|
||||
s2 := []int{2, 4}
|
||||
res := slice.Merge(s1, s2)
|
||||
|
||||
fmt.Println(res) //[]int{1, 2, 3, 2, 4}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="Reverse">Reverse</span>
|
||||
|
||||
<p>反转切片中的元素顺序</p>
|
||||
@@ -1018,6 +1079,30 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="Repeat">Repeat</span>
|
||||
|
||||
<p>创建一个切片,包含n个传入的item</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func Repeat[T any](item T, n int) []T
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/slice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println(slice.Repeat("a", 3)) //[]string{"a", "a", "a"}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="Shuffle">Shuffle</span>
|
||||
|
||||
<p>随机打乱切片中的元素顺序</p>
|
||||
@@ -1043,7 +1128,93 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="SortByField">SortByField</span>
|
||||
### <span id="Sort">Sort</span>
|
||||
|
||||
<p>对任何有序类型(数字或字符串)的切片进行排序,使用快速排序算法。 默认排序顺序为升序 (asc),如果需要降序,请将参数 `sortOrder` 设置为 `desc`。 Ordered类型:数字(所有整数浮点数)或字符串。</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func Sort[T lancetconstraints.Ordered](slice []T, sortOrder ...string)
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/slice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
numbers := []int{1, 4, 3, 2, 5}
|
||||
|
||||
slice.Sort(numbers)
|
||||
fmt.Println(numbers) //{1,2,3,4,5}
|
||||
|
||||
slice.Sort(numbers, "desc")
|
||||
fmt.Println(numbers) //{5,4,3,2,1}
|
||||
|
||||
strings := []string{"a", "d", "c", "b", "e"}
|
||||
|
||||
slice.Sort(strings)
|
||||
fmt.Println(strings) //{"a", "b", "c", "d", "e"}
|
||||
|
||||
slice.Sort(strings, "desc")
|
||||
fmt.Println(strings) //{"e", "d", "c", "b", "a"}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="SortBy">SortBy</span>
|
||||
|
||||
<p>按照less函数确定的升序规则对切片进行排序。排序不保证稳定性</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func SortBy[T any](slice []T, less func(a, b T) bool)
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/slice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
numbers := []int{1, 4, 3, 2, 5}
|
||||
|
||||
slice.SortBy(numbers, func(a, b int) bool {
|
||||
return a < b
|
||||
})
|
||||
fmt.Println(numbers) //{1, 2, 3, 4, 5}
|
||||
|
||||
type User struct {
|
||||
Name string
|
||||
Age uint
|
||||
}
|
||||
|
||||
users := []User{
|
||||
{Name: "a", Age: 21},
|
||||
{Name: "b", Age: 15},
|
||||
{Name: "c", Age: 100}}
|
||||
|
||||
slice.SortBy(users, func(a, b User) bool {
|
||||
return a.Age < b.Age
|
||||
})
|
||||
|
||||
fmt.Printf("sort users by age: %v", users)
|
||||
|
||||
// output
|
||||
// [{b 15} {a 21} {c 100}]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### <span id="SortByField">SortByField (已弃用: 请使用 Sort或SortBy 代替该方法)</span>
|
||||
|
||||
<p>按字段对结构切片进行排序。slice元素应为struct,字段类型应为int、uint、string或bool。 默认排序类型是升序(asc),如果是降序,设置 sortType 为 desc</p>
|
||||
|
||||
@@ -1115,7 +1286,7 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="StringSlice">StringSlice</span>
|
||||
### <span id="StringSlice">StringSlice(已弃用: 使用go1.18+泛型代替)</span>
|
||||
|
||||
<p>将接口切片转换为字符串切片</p>
|
||||
|
||||
@@ -1176,7 +1347,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func ToSlice[T any](value ...T) []T
|
||||
func ToSlice[T any](items ...T) []T
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
@@ -1200,7 +1371,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func ToSlicePointer[T any](value ...T) []*T
|
||||
func ToSlicePointer[T any](items ...T) []*T
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
@@ -1356,7 +1527,7 @@ func main() {
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func Without[T comparable](slice []T, values ...T) []T
|
||||
func Without[T comparable](slice []T, items ...T) []T
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
|
||||
@@ -36,7 +36,6 @@ import (
|
||||
- [SnakeCase](#SnakeCase)
|
||||
- [SplitEx](#SplitEx)
|
||||
- [Wrap](#Wrap)
|
||||
|
||||
- [Unwrap](#Unwrap)
|
||||
|
||||
|
||||
|
||||
@@ -36,7 +36,6 @@ import (
|
||||
- [SnakeCase](#SnakeCase)
|
||||
- [SplitEx](#SplitEx)
|
||||
- [Wrap](#Wrap)
|
||||
|
||||
- [Unwrap](#Unwrap)
|
||||
|
||||
|
||||
|
||||
@@ -211,7 +211,7 @@ func main() {
|
||||
|
||||
|
||||
### <span id="ExecCommand">CompareOsEnv</span>
|
||||
<p>Use shell /bin/bash -c(linux) or cmd (windows) to execute command.</p>
|
||||
<p>Execute shell command, return the stdout and stderr string of command, and error if error occur. param `command` is a complete command string, like, ls -a (linux), dir(windows), ping 127.0.0.1. In linux, use /bin/bash -c to execute command, In windows, use powershell.exe to execute command.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
@@ -227,10 +227,24 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
out, errout, err := system.ExecCommand("ls")
|
||||
fmt.Println(out)
|
||||
fmt.Println(errout)
|
||||
fmt.Println(err)
|
||||
// linux or mac
|
||||
stdout, stderr, err := system.ExecCommand("ls")
|
||||
fmt.Println("std out: ", stdout)
|
||||
fmt.Println("std err: ", stderr)
|
||||
assert.Equal("", stderr)
|
||||
|
||||
// windows
|
||||
stdout, stderr, err = system.ExecCommand("dir")
|
||||
fmt.Println("std out: ", stdout)
|
||||
fmt.Println("std err: ", stderr)
|
||||
|
||||
// error command
|
||||
stdout, stderr, err = system.ExecCommand("abc")
|
||||
fmt.Println("std out: ", stdout)
|
||||
fmt.Println("std err: ", stderr)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -212,7 +212,7 @@ func main() {
|
||||
|
||||
|
||||
### <span id="ExecCommand">ExecCommand</span>
|
||||
<p>使用shell /bin/bash -c(linux) 或 cmd (windows) 执行shell命令</p>
|
||||
<p>执行shell命令,返回命令的stdout和stderr字符串,如果出现错误,则返回错误。参数`command`是一个完整的命令字符串,如ls-a(linux),dir(windows),ping 127.0.0.1。在linux中,使用/bin/bash-c执行命令,在windows中,使用powershell.exe执行命令。</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
@@ -228,10 +228,24 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
out, errout, err := system.ExecCommand("ls")
|
||||
fmt.Println(out)
|
||||
fmt.Println(errout)
|
||||
fmt.Println(err)
|
||||
// linux or mac
|
||||
stdout, stderr, err := system.ExecCommand("ls")
|
||||
fmt.Println("std out: ", stdout)
|
||||
fmt.Println("std err: ", stderr)
|
||||
assert.Equal("", stderr)
|
||||
|
||||
// windows
|
||||
stdout, stderr, err = system.ExecCommand("dir")
|
||||
fmt.Println("std out: ", stdout)
|
||||
fmt.Println("std err: ", stderr)
|
||||
|
||||
// error command
|
||||
stdout, stderr, err = system.ExecCommand("abc")
|
||||
fmt.Println("std out: ", stdout)
|
||||
fmt.Println("std err: ", stderr)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -34,7 +34,6 @@ import (
|
||||
- [IsCreditCard](#IsCreditCard)
|
||||
- [IsDns](#IsDns)
|
||||
- [IsEmail](#IsEmail)
|
||||
|
||||
- [IsEmptyString](#IsEmptyString)
|
||||
- [IsFloatStr](#IsFloatStr)
|
||||
- [IsNumberStr](#IsNumberStr)
|
||||
@@ -48,6 +47,7 @@ import (
|
||||
- [IsUrl](#IsUrl)
|
||||
- [IsWeakPassword](#IsWeakPassword)
|
||||
- [IsZeroValue](#IsZeroValue)
|
||||
- [IsGBK](#IsGBK)
|
||||
|
||||
|
||||
<div STYLE="page-break-after: always;"></div>
|
||||
@@ -822,7 +822,34 @@ func main() {
|
||||
```
|
||||
|
||||
|
||||
|
||||
### <span id="IsGBK">IsGBK</span>
|
||||
<p>Checks if data encoding is gbk(Chinese character internal code extension specification). this function is implemented by whether double bytes fall within the encoding range of gbk,while each byte of utf-8 encoding format falls within the encoding range of gbk.Therefore, utf8.valid() should be called first to check whether it is not utf-8 encoding and then call IsGBK() to check gbk encoding. like the example.</p>
|
||||
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func IsGBK(data []byte) bool
|
||||
```
|
||||
<b>Example:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/validator"
|
||||
)
|
||||
|
||||
func main() {
|
||||
data := []byte("你好")
|
||||
|
||||
// check utf8 first
|
||||
if utf8.Valid(data) {
|
||||
fmt.Println("data encoding is utf-8")
|
||||
}else if(validator.IsGBK(data)) {
|
||||
fmt.Println("data encoding is GBK")
|
||||
}
|
||||
fmt.Println("data encoding is unknown")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -34,7 +34,6 @@ import (
|
||||
- [IsCreditCard](#IsCreditCard)
|
||||
- [IsDns](#IsDns)
|
||||
- [IsEmail](#IsEmail)
|
||||
|
||||
- [IsEmptyString](#IsEmptyString)
|
||||
- [IsFloatStr](#IsFloatStr)
|
||||
- [IsNumberStr](#IsNumberStr)
|
||||
@@ -48,6 +47,7 @@ import (
|
||||
- [IsUrl](#IsUrl)
|
||||
- [IsWeakPassword](#IsWeakPassword)
|
||||
- [IsZeroValue](#IsZeroValue)
|
||||
- [IsGBK](#IsGBK)
|
||||
|
||||
|
||||
<div STYLE="page-break-after: always;"></div>
|
||||
@@ -821,3 +821,31 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
### <span id="IsGBK">IsGBK</span>
|
||||
<p>检查数据编码是否为gbk(汉字内部代码扩展规范)。该函数的实现取决于双字节是否在gbk的编码范围内,而utf-8编码格式的每个字节都在gbk编码范围内。因此,应该首先调用utf8.valid检查它是否是utf-8编码,然后调用IsGBK检查gbk编码。如示例所示。</p>
|
||||
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func IsGBK(data []byte) bool
|
||||
```
|
||||
<b>例子:</b>
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/duke-git/lancet/v2/validator"
|
||||
)
|
||||
|
||||
func main() {
|
||||
data := []byte("你好")
|
||||
|
||||
// 先检查utf8编码
|
||||
if utf8.Valid(data) {
|
||||
fmt.Println("data encoding is utf-8")
|
||||
}else if(validator.IsGBK(data)) {
|
||||
fmt.Println("data encoding is GBK")
|
||||
}
|
||||
fmt.Println("data encoding is unknown")
|
||||
}
|
||||
```
|
||||
@@ -222,8 +222,6 @@ func UnZip(zipFile string, destPath string) error {
|
||||
defer zipReader.Close()
|
||||
|
||||
for _, f := range zipReader.File {
|
||||
path := filepath.Join(destPath, f.Name)
|
||||
|
||||
//issue#62: fix ZipSlip bug
|
||||
path, err := safeFilepathJoin(destPath, f.Name)
|
||||
if err != nil {
|
||||
|
||||
2
go.mod
2
go.mod
@@ -1,3 +1,5 @@
|
||||
module github.com/duke-git/lancet/v2
|
||||
|
||||
go 1.18
|
||||
|
||||
require golang.org/x/text v0.5.0
|
||||
|
||||
2
go.sum
Normal file
2
go.sum
Normal file
@@ -0,0 +1,2 @@
|
||||
golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM=
|
||||
golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
174
iterator/iterator.go
Normal file
174
iterator/iterator.go
Normal file
@@ -0,0 +1,174 @@
|
||||
// Copyright 2022 dudaodong@gmail.com. All rights resulterved.
|
||||
// Use of this source code is governed by MIT license
|
||||
|
||||
// Package iterator provides a way to iterate over values stored in containers.
|
||||
// note:
|
||||
// 1. Full feature iterator is complicated, this package is just a experiment to explore how iterators could work in Go.
|
||||
// 2. The functionality of this package is very simple and limited, may not meet the actual dev needs.
|
||||
// 3. It is currently under development, unstable, and will not be completed for some time in the future.
|
||||
// So, based on above factors, you may not use it in production. but, anyone is welcome to improve it.
|
||||
// Hope that Go can support iterator in future. see https://github.com/golang/go/discussions/54245 and https://github.com/golang/go/discussions/56413
|
||||
package iterator
|
||||
|
||||
import "github.com/duke-git/lancet/v2/lancetconstraints"
|
||||
|
||||
// Iterator supports iterating over a sequence of values of type `E`.
|
||||
type Iterator[T any] interface {
|
||||
// Next checks if there is a next value in the iteration or not
|
||||
HasNext() bool
|
||||
// Next returns the next value in the iteration if there is one,
|
||||
// and reports whether the returned value is valid.
|
||||
// Once Next returns ok==false, the iteration is over,
|
||||
// and all subsequent calls will return ok==false.
|
||||
Next() (item T, ok bool)
|
||||
}
|
||||
|
||||
// StopIterator is an interface for stopping Iterator.
|
||||
type StopIterator[T any] interface {
|
||||
Iterator[T]
|
||||
|
||||
// Stop indicates that the iterator will no longer be used.
|
||||
// After a call to Stop, future calls to Next may panic.
|
||||
// Stop may be called multiple times;
|
||||
// all calls after the first will have no effect.
|
||||
Stop()
|
||||
}
|
||||
|
||||
// DeleteIter is an Iter that implements a Delete method.
|
||||
type DeleteIterator[T any] interface {
|
||||
Iterator[T]
|
||||
|
||||
// Delete deletes the current iterator element;
|
||||
// that is, the one returned by the last call to Next.
|
||||
// Delete should panic if called before Next or after
|
||||
// Next returns false.
|
||||
Delete()
|
||||
}
|
||||
|
||||
// SetIterator is an Iter that implements a Set method.
|
||||
type SetIterator[T any] interface {
|
||||
Iterator[T]
|
||||
|
||||
// Set replaces the current iterator element with v.
|
||||
// Set should panic if called before Next or after
|
||||
// Next returns false.
|
||||
Set(v T)
|
||||
}
|
||||
|
||||
// PrevIterator is an iterator with a Prev method.
|
||||
type PrevIterator[T any] interface {
|
||||
Iterator[T]
|
||||
|
||||
// Prev moves the iterator to the previous position.
|
||||
// After calling Prev, Next will return the value at
|
||||
// that position in the container. For example, after
|
||||
// it.Next() returning (v, true)
|
||||
// it.Prev()
|
||||
// another call to it.Next will again return (v, true).
|
||||
// Calling Prev before calling Next may panic.
|
||||
// Calling Prev after Next returns false will move
|
||||
// to the last element, or, if there are no elements,
|
||||
// to the iterator's initial state.
|
||||
Prev()
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Functions that create an Iterator from some other type. //
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// FromSlice returns an iterator over a slice of data.
|
||||
func FromSlice[T any](slice []T) Iterator[T] {
|
||||
return &sliceIterator[T]{slice: slice, index: -1}
|
||||
}
|
||||
|
||||
func ToSlice[T any](iter Iterator[T]) []T {
|
||||
result := []T{}
|
||||
for item, ok := iter.Next(); ok; item, ok = iter.Next() {
|
||||
result = append(result, item)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
type sliceIterator[T any] struct {
|
||||
slice []T
|
||||
index int
|
||||
}
|
||||
|
||||
func (iter *sliceIterator[T]) HasNext() bool {
|
||||
return iter.index < len(iter.slice)-1
|
||||
}
|
||||
|
||||
func (iter *sliceIterator[T]) Next() (T, bool) {
|
||||
iter.index++
|
||||
ok := iter.index >= 0 && iter.index < len(iter.slice)
|
||||
var item T
|
||||
if ok {
|
||||
item = iter.slice[iter.index]
|
||||
}
|
||||
return item, ok
|
||||
|
||||
// if len(iter.slice) == 0 {
|
||||
// var zero T
|
||||
// return zero, false
|
||||
// }
|
||||
// iter.index++
|
||||
// item := iter.slice[0]
|
||||
// iter.slice = iter.slice[1:]
|
||||
// return item, true
|
||||
}
|
||||
|
||||
// Prev implements PrevIterator.
|
||||
func (iter *sliceIterator[T]) Prev() {
|
||||
if iter.index == -1 {
|
||||
panic("Next function should be called Prev")
|
||||
}
|
||||
if iter.HasNext() {
|
||||
iter.index--
|
||||
} else {
|
||||
iter.index = len(iter.slice) - 1
|
||||
}
|
||||
}
|
||||
|
||||
// Set implements SetIterator.
|
||||
func (iter *sliceIterator[T]) Set(value T) {
|
||||
if iter.index == -1 {
|
||||
panic("Next function should be called Set")
|
||||
}
|
||||
if iter.index >= len(iter.slice) || len(iter.slice) == 0 {
|
||||
panic("No element in current iterator")
|
||||
}
|
||||
iter.slice[iter.index] = value
|
||||
}
|
||||
|
||||
// FromRange creates a iterator which returns the numeric range between start inclusive and end
|
||||
// exclusive by the step size. start should be less than end, step shoud be positive.
|
||||
func FromRange[T lancetconstraints.Number](start, end, step T) Iterator[T] {
|
||||
if end < start {
|
||||
panic("RangeIterator: start should be before end")
|
||||
} else if step <= 0 {
|
||||
panic("RangeIterator: step should be positive")
|
||||
}
|
||||
|
||||
return &rangeIterator[T]{start: start, end: end, step: step}
|
||||
}
|
||||
|
||||
type rangeIterator[T lancetconstraints.Number] struct {
|
||||
start, end, step T
|
||||
}
|
||||
|
||||
func (iter *rangeIterator[T]) HasNext() bool {
|
||||
if iter.start >= iter.end {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (iter *rangeIterator[T]) Next() (T, bool) {
|
||||
if iter.start >= iter.end {
|
||||
var zero T
|
||||
return zero, false
|
||||
}
|
||||
num := iter.start
|
||||
iter.start += iter.step
|
||||
return num, true
|
||||
}
|
||||
50
iterator/iterator_test.go
Normal file
50
iterator/iterator_test.go
Normal file
@@ -0,0 +1,50 @@
|
||||
// Copyright 2022 dudaodong@gmail.com. All rights resulterved.
|
||||
// Use of this source code is governed by MIT license
|
||||
|
||||
// Package iterator implements some feature of C++ STL iterators
|
||||
package iterator
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/duke-git/lancet/v2/internal"
|
||||
)
|
||||
|
||||
func TestSliceIterator(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSliceIterator")
|
||||
|
||||
// HashNext
|
||||
t.Run("slice iterator HasNext: ", func(t *testing.T) {
|
||||
iter1 := FromSlice([]int{1, 2, 3, 4})
|
||||
for {
|
||||
item, _ := iter1.Next()
|
||||
|
||||
if item == 4 {
|
||||
assert.Equal(false, iter1.HasNext())
|
||||
break
|
||||
} else {
|
||||
assert.Equal(true, iter1.HasNext())
|
||||
}
|
||||
}
|
||||
|
||||
iter2 := FromSlice([]int{})
|
||||
assert.Equal(false, iter2.HasNext())
|
||||
})
|
||||
|
||||
//Next
|
||||
t.Run("slice iterator Next: ", func(t *testing.T) {
|
||||
iter1 := FromSlice([]int{1, 2, 3, 4})
|
||||
for i := 0; i < 4; i++ {
|
||||
item, ok := iter1.Next()
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
assert.Equal(i+1, item)
|
||||
}
|
||||
|
||||
iter2 := FromSlice([]int{})
|
||||
_, ok := iter2.Next()
|
||||
assert.Equal(false, ok)
|
||||
})
|
||||
|
||||
}
|
||||
61
iterator/operation.go
Normal file
61
iterator/operation.go
Normal file
@@ -0,0 +1,61 @@
|
||||
// Copyright 2022 dudaodong@gmail.com. All rights resulterved.
|
||||
// Use of this source code is governed by MIT license
|
||||
|
||||
// Package iterator provides a way to iterate over values stored in containers.
|
||||
// note:
|
||||
// 1. Full feature iterator is complicated, this package is just a experiment to explore how iterators could work in Go.
|
||||
// 2. The functionality of this package is very simple and limited, may not meet the actual dev needs.
|
||||
// 3. It is currently under development, unstable, and will not be completed for some time in the future.
|
||||
// So, based on above factors, you may not use it in production. but, anyone is welcome to improve it.
|
||||
// Hope that Go can support iterator in future. see https://github.com/golang/go/discussions/54245 and https://github.com/golang/go/discussions/56413
|
||||
package iterator
|
||||
|
||||
// Map creates a new iterator which applies a function to all items of input iterator.
|
||||
func Map[T any, U any](iter Iterator[T], iteratee func(item T) U) Iterator[U] {
|
||||
return &mapIterator[T, U]{
|
||||
iter: iter,
|
||||
iteratee: iteratee,
|
||||
}
|
||||
}
|
||||
|
||||
type mapIterator[T any, U any] struct {
|
||||
iter Iterator[T]
|
||||
iteratee func(T) U
|
||||
}
|
||||
|
||||
func (mr *mapIterator[T, U]) HasNext() bool {
|
||||
return mr.iter.HasNext()
|
||||
}
|
||||
|
||||
func (mr *mapIterator[T, U]) Next() (U, bool) {
|
||||
var zero U
|
||||
item, ok := mr.iter.Next()
|
||||
if !ok {
|
||||
return zero, false
|
||||
}
|
||||
return mr.iteratee(item), true
|
||||
}
|
||||
|
||||
// Filter creates a new iterator that returns only the items that pass specified predicate function.
|
||||
func Filter[T any](iter Iterator[T], predicateFunc func(item T) bool) Iterator[T] {
|
||||
return &filterIterator[T]{iter: iter, predicateFunc: predicateFunc}
|
||||
}
|
||||
|
||||
type filterIterator[T any] struct {
|
||||
iter Iterator[T]
|
||||
predicateFunc func(T) bool
|
||||
}
|
||||
|
||||
func (fr *filterIterator[T]) Next() (T, bool) {
|
||||
for item, ok := fr.iter.Next(); ok; item, ok = fr.iter.Next() {
|
||||
if fr.predicateFunc(item) {
|
||||
return item, true
|
||||
}
|
||||
}
|
||||
var zero T
|
||||
return zero, false
|
||||
}
|
||||
|
||||
func (fr *filterIterator[T]) HasNext() bool {
|
||||
return fr.iter.HasNext()
|
||||
}
|
||||
@@ -16,3 +16,8 @@ type Comparator interface {
|
||||
type Number interface {
|
||||
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64
|
||||
}
|
||||
|
||||
// Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >
|
||||
type Ordered interface {
|
||||
Number | ~string
|
||||
}
|
||||
|
||||
274
slice/slice.go
274
slice/slice.go
@@ -10,22 +10,31 @@ import (
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"sort"
|
||||
|
||||
"github.com/duke-git/lancet/v2/lancetconstraints"
|
||||
)
|
||||
|
||||
// Contain check if the value is in the slice or not
|
||||
func Contain[T comparable](slice []T, value T) bool {
|
||||
set := make(map[T]struct{}, len(slice))
|
||||
for _, v := range slice {
|
||||
set[v] = struct{}{}
|
||||
// Create a static variable to store the hash table.
|
||||
// This variable has the same lifetime as the entire program and can be shared by functions that are called more than once.
|
||||
var (
|
||||
memoryHashMap = make(map[string]map[any]int)
|
||||
memoryHashCounter = make(map[string]int)
|
||||
)
|
||||
|
||||
// Contain check if the target value is in the slice or not
|
||||
func Contain[T comparable](slice []T, target T) bool {
|
||||
for _, item := range slice {
|
||||
if item == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
_, ok := set[value]
|
||||
return ok
|
||||
return false
|
||||
}
|
||||
|
||||
// ContainSubSlice check if the slice contain subslice or not
|
||||
func ContainSubSlice[T comparable](slice, subslice []T) bool {
|
||||
for _, v := range subslice {
|
||||
// ContainSubSlice check if the slice contain a given subslice or not
|
||||
func ContainSubSlice[T comparable](slice, subSlice []T) bool {
|
||||
for _, v := range subSlice {
|
||||
if !Contain(slice, v) {
|
||||
return false
|
||||
}
|
||||
@@ -34,7 +43,7 @@ func ContainSubSlice[T comparable](slice, subslice []T) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Chunk creates an slice of elements split into groups the length of size.
|
||||
// Chunk creates a slice of elements split into groups the length of size
|
||||
func Chunk[T any](slice []T, size int) [][]T {
|
||||
result := [][]T{}
|
||||
|
||||
@@ -42,39 +51,27 @@ func Chunk[T any](slice []T, size int) [][]T {
|
||||
return result
|
||||
}
|
||||
|
||||
length := len(slice)
|
||||
if size == 1 || size >= length {
|
||||
for _, v := range slice {
|
||||
var tmp []T
|
||||
tmp = append(tmp, v)
|
||||
result = append(result, tmp)
|
||||
for _, item := range slice {
|
||||
l := len(result)
|
||||
if l == 0 || len(result[l-1]) == size {
|
||||
result = append(result, []T{})
|
||||
l++
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// divide slice equally
|
||||
divideNum := length/size + 1
|
||||
for i := 0; i < divideNum; i++ {
|
||||
if i == divideNum-1 {
|
||||
if len(slice[i*size:]) > 0 {
|
||||
result = append(result, slice[i*size:])
|
||||
}
|
||||
} else {
|
||||
result = append(result, slice[i*size:(i+1)*size])
|
||||
}
|
||||
result[l-1] = append(result[l-1], item)
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
}
|
||||
|
||||
// Compact creates an slice with all falsey values removed. The values false, nil, 0, and "" are falsey
|
||||
func Compact[T any](slice []T) []T {
|
||||
result := make([]T, 0)
|
||||
func Compact[T comparable](slice []T) []T {
|
||||
var zero T
|
||||
|
||||
result := []T{}
|
||||
for _, v := range slice {
|
||||
if !reflect.DeepEqual(v, nil) &&
|
||||
!reflect.DeepEqual(v, false) &&
|
||||
!reflect.DeepEqual(v, "") &&
|
||||
!reflect.DeepEqual(v, 0) {
|
||||
if v != zero {
|
||||
result = append(result, v)
|
||||
}
|
||||
}
|
||||
@@ -82,11 +79,11 @@ func Compact[T any](slice []T) []T {
|
||||
return result
|
||||
}
|
||||
|
||||
// Concat creates a new slice concatenating slice with any additional slices and/or values.
|
||||
func Concat[T any](slice []T, values ...[]T) []T {
|
||||
// Concat creates a new slice concatenating slice with any additional slices.
|
||||
func Concat[T any](slice []T, slices ...[]T) []T {
|
||||
result := append([]T{}, slice...)
|
||||
|
||||
for _, v := range values {
|
||||
for _, v := range slices {
|
||||
result = append(result, v...)
|
||||
}
|
||||
|
||||
@@ -124,7 +121,7 @@ func DifferenceBy[T comparable](slice []T, comparedSlice []T, iteratee func(inde
|
||||
}
|
||||
|
||||
//DifferenceWith accepts comparator which is invoked to compare elements of slice to values. The order and references of result values are determined by the first slice. The comparator is invoked with two arguments: (arrVal, othVal).
|
||||
func DifferenceWith[T any](slice []T, comparedSlice []T, comparator func(value1, value2 T) bool) []T {
|
||||
func DifferenceWith[T any](slice []T, comparedSlice []T, comparator func(item1, item2 T) bool) []T {
|
||||
result := make([]T, 0)
|
||||
|
||||
getIndex := func(arr []T, item T, comparison func(v1, v2 T) bool) int {
|
||||
@@ -169,9 +166,8 @@ func EqualWith[T, U any](slice1 []T, slice2 []U, comparator func(T, U) bool) boo
|
||||
return false
|
||||
}
|
||||
|
||||
for i, v1 := range slice1 {
|
||||
v2 := slice2[i]
|
||||
if !comparator(v1, v2) {
|
||||
for i, v := range slice1 {
|
||||
if !comparator(v, slice2[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -181,33 +177,29 @@ func EqualWith[T, U any](slice1 []T, slice2 []U, comparator func(T, U) bool) boo
|
||||
|
||||
// Every return true if all of the values in the slice pass the predicate function.
|
||||
func Every[T any](slice []T, predicate func(index int, item T) bool) bool {
|
||||
var currentLength int
|
||||
|
||||
for i, v := range slice {
|
||||
if predicate(i, v) {
|
||||
currentLength++
|
||||
if !predicate(i, v) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return currentLength == len(slice)
|
||||
return true
|
||||
}
|
||||
|
||||
// None return true if all the values in the slice mismatch the criteria
|
||||
func None[T any](slice []T, predicate func(index int, item T) bool) bool {
|
||||
|
||||
var currentLength int
|
||||
l := 0
|
||||
for i, v := range slice {
|
||||
if !predicate(i, v) {
|
||||
currentLength++
|
||||
l++
|
||||
}
|
||||
}
|
||||
|
||||
return currentLength == len(slice)
|
||||
return l == len(slice)
|
||||
}
|
||||
|
||||
// Some return true if any of the values in the list pass the predicate function.
|
||||
func Some[T any](slice []T, predicate func(index int, item T) bool) bool {
|
||||
|
||||
for i, v := range slice {
|
||||
if predicate(i, v) {
|
||||
return true
|
||||
@@ -220,6 +212,7 @@ func Some[T any](slice []T, predicate func(index int, item T) bool) bool {
|
||||
// Filter iterates over elements of slice, returning an slice of all elements pass the predicate function
|
||||
func Filter[T any](slice []T, predicate func(index int, item T) bool) []T {
|
||||
result := make([]T, 0)
|
||||
|
||||
for i, v := range slice {
|
||||
if predicate(i, v) {
|
||||
result = append(result, v)
|
||||
@@ -229,13 +222,23 @@ func Filter[T any](slice []T, predicate func(index int, item T) bool) []T {
|
||||
return result
|
||||
}
|
||||
|
||||
// Count iterates over elements of slice, returns a count of all matched elements
|
||||
func Count[T any](slice []T, predicate func(index int, item T) bool) int {
|
||||
if len(slice) == 0 {
|
||||
return 0
|
||||
// Count returns the number of occurrences of the given item in the slice
|
||||
func Count[T comparable](slice []T, item T) int {
|
||||
count := 0
|
||||
|
||||
for _, v := range slice {
|
||||
if item == v {
|
||||
count++
|
||||
}
|
||||
}
|
||||
|
||||
var count int
|
||||
return count
|
||||
}
|
||||
|
||||
// CountBy iterates over elements of slice with predicate function, returns the number of all matched elements
|
||||
func CountBy[T any](slice []T, predicate func(index int, item T) bool) int {
|
||||
count := 0
|
||||
|
||||
for i, v := range slice {
|
||||
if predicate(i, v) {
|
||||
count++
|
||||
@@ -284,11 +287,8 @@ func GroupWith[T any, U comparable](slice []T, iteratee func(item T) U) map[U][]
|
||||
// Find iterates over elements of slice, returning the first one that passes a truth test on predicate function.
|
||||
// If return T is nil then no items matched the predicate func
|
||||
func Find[T any](slice []T, predicate func(index int, item T) bool) (*T, bool) {
|
||||
if len(slice) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
index := -1
|
||||
|
||||
for i, v := range slice {
|
||||
if predicate(i, v) {
|
||||
index = i
|
||||
@@ -306,11 +306,8 @@ func Find[T any](slice []T, predicate func(index int, item T) bool) (*T, bool) {
|
||||
// FindLast iterates over elements of slice from end to begin, returning the first one that passes a truth test on predicate function.
|
||||
// If return T is nil then no items matched the predicate func
|
||||
func FindLast[T any](slice []T, predicate func(index int, item T) bool) (*T, bool) {
|
||||
if len(slice) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
index := -1
|
||||
|
||||
for i := len(slice) - 1; i >= 0; i-- {
|
||||
if predicate(i, slice[i]) {
|
||||
index = i
|
||||
@@ -356,8 +353,11 @@ func Flatten(slice any) any {
|
||||
func FlattenDeep(slice any) any {
|
||||
sv := sliceValue(slice)
|
||||
st := sliceElemType(sv.Type())
|
||||
|
||||
tmp := reflect.MakeSlice(reflect.SliceOf(st), 0, 0)
|
||||
|
||||
result := flattenRecursive(sv, tmp)
|
||||
|
||||
return result.Interface()
|
||||
}
|
||||
|
||||
@@ -386,6 +386,7 @@ func ForEach[T any](slice []T, iteratee func(index int, item T)) {
|
||||
// Map creates an slice of values by running each element of slice thru iteratee function.
|
||||
func Map[T any, U any](slice []T, iteratee func(index int, item T) U) []U {
|
||||
result := make([]U, len(slice), cap(slice))
|
||||
|
||||
for i, v := range slice {
|
||||
result[i] = iteratee(i, v)
|
||||
}
|
||||
@@ -395,7 +396,6 @@ func Map[T any, U any](slice []T, iteratee func(index int, item T) U) []U {
|
||||
|
||||
// Reduce creates an slice of values by running each element of slice thru iteratee function.
|
||||
func Reduce[T any](slice []T, iteratee func(index int, item1, item2 T) T, initial T) T {
|
||||
|
||||
if len(slice) == 0 {
|
||||
return initial
|
||||
}
|
||||
@@ -432,7 +432,19 @@ func ReplaceAll[T comparable](slice []T, old T, new T) []T {
|
||||
return Replace(slice, old, new, -1)
|
||||
}
|
||||
|
||||
// Repeat creates a slice with length n whose elements are param `item`.
|
||||
func Repeat[T any](item T, n int) []T {
|
||||
result := make([]T, n)
|
||||
|
||||
for i := range result {
|
||||
result[i] = item
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// InterfaceSlice convert param to slice of interface.
|
||||
// This function is deprecated, use generics feature of go1.18+ for replacement
|
||||
func InterfaceSlice(slice any) []any {
|
||||
sv := sliceValue(slice)
|
||||
if sv.IsNil() {
|
||||
@@ -448,35 +460,37 @@ func InterfaceSlice(slice any) []any {
|
||||
}
|
||||
|
||||
// StringSlice convert param to slice of string.
|
||||
// This function is deprecated, use generics feature of go1.18+ for replacement
|
||||
func StringSlice(slice any) []string {
|
||||
v := sliceValue(slice)
|
||||
|
||||
out := make([]string, v.Len())
|
||||
result := make([]string, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
v, ok := v.Index(i).Interface().(string)
|
||||
if !ok {
|
||||
panic("invalid element type")
|
||||
}
|
||||
out[i] = v
|
||||
result[i] = v
|
||||
}
|
||||
|
||||
return out
|
||||
return result
|
||||
}
|
||||
|
||||
// IntSlice convert param to slice of int.
|
||||
// This function is deprecated, use generics feature of go1.18+ for replacement
|
||||
func IntSlice(slice any) []int {
|
||||
sv := sliceValue(slice)
|
||||
|
||||
out := make([]int, sv.Len())
|
||||
result := make([]int, sv.Len())
|
||||
for i := 0; i < sv.Len(); i++ {
|
||||
v, ok := sv.Index(i).Interface().(int)
|
||||
if !ok {
|
||||
panic("invalid element type")
|
||||
}
|
||||
out[i] = v
|
||||
result[i] = v
|
||||
}
|
||||
|
||||
return out
|
||||
return result
|
||||
}
|
||||
|
||||
// DeleteAt delete the element of slice from start index to end index - 1.
|
||||
@@ -594,7 +608,7 @@ func UniqueBy[T comparable](slice []T, iteratee func(item T) T) []T {
|
||||
return Unique(result)
|
||||
}
|
||||
|
||||
// Union creates a slice of unique values, in order, from all given slices.
|
||||
// Union creates a slice of unique elements, in order, from all given slices.
|
||||
func Union[T comparable](slices ...[]T) []T {
|
||||
result := []T{}
|
||||
contain := map[T]struct{}{}
|
||||
@@ -629,7 +643,18 @@ func UnionBy[T any, V comparable](predicate func(item T) V, slices ...[]T) []T {
|
||||
return result
|
||||
}
|
||||
|
||||
// Intersection creates a slice of unique values that included by all slices.
|
||||
// Merge all given slices into one slice
|
||||
func Merge[T any](slices ...[]T) []T {
|
||||
result := make([]T, 0)
|
||||
|
||||
for _, v := range slices {
|
||||
result = append(result, v...)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Intersection creates a slice of unique elements that included by all slices.
|
||||
func Intersection[T comparable](slices ...[]T) []T {
|
||||
if len(slices) == 0 {
|
||||
return []T{}
|
||||
@@ -640,8 +665,8 @@ func Intersection[T comparable](slices ...[]T) []T {
|
||||
|
||||
reducer := func(sliceA, sliceB []T) []T {
|
||||
hashMap := make(map[T]int)
|
||||
for _, val := range sliceA {
|
||||
hashMap[val] = 1
|
||||
for _, v := range sliceA {
|
||||
hashMap[v] = 1
|
||||
}
|
||||
|
||||
out := make([]T, 0)
|
||||
@@ -709,9 +734,26 @@ func Shuffle[T any](slice []T) []T {
|
||||
return result
|
||||
}
|
||||
|
||||
// Sort sorts a slice of any ordered type(number or string), use quick sort algrithm.
|
||||
// default sort order is ascending (asc), if want descending order, set param `sortOrder` to `desc`
|
||||
func Sort[T lancetconstraints.Ordered](slice []T, sortOrder ...string) {
|
||||
if len(sortOrder) > 0 && sortOrder[0] == "desc" {
|
||||
quickSort(slice, 0, len(slice)-1, "desc")
|
||||
} else {
|
||||
quickSort(slice, 0, len(slice)-1, "asc")
|
||||
}
|
||||
}
|
||||
|
||||
// SortBy sorts the slice in ascending order as determined by the less function.
|
||||
// This sort is not guaranteed to be stable
|
||||
func SortBy[T any](slice []T, less func(a, b T) bool) {
|
||||
quickSortBy(slice, 0, len(slice)-1, less)
|
||||
}
|
||||
|
||||
// SortByField return sorted slice by field
|
||||
// Slice element should be struct, field type should be int, uint, string, or bool
|
||||
// slice element should be struct, field type should be int, uint, string, or bool
|
||||
// default sortType is ascending (asc), if descending order, set sortType to desc
|
||||
// This function is deprecated, use Sort and SortBy for replacement
|
||||
func SortByField(slice any, field string, sortType ...string) error {
|
||||
sv := sliceValue(slice)
|
||||
t := sv.Type().Elem()
|
||||
@@ -781,15 +823,15 @@ func SortByField(slice any, field string, sortType ...string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Without creates a slice excluding all given values
|
||||
func Without[T comparable](slice []T, values ...T) []T {
|
||||
if len(values) == 0 || len(slice) == 0 {
|
||||
// Without creates a slice excluding all given items
|
||||
func Without[T comparable](slice []T, items ...T) []T {
|
||||
if len(items) == 0 || len(slice) == 0 {
|
||||
return slice
|
||||
}
|
||||
|
||||
result := make([]T, 0, len(slice))
|
||||
for _, v := range slice {
|
||||
if !Contain(values, v) {
|
||||
if !Contain(items, v) {
|
||||
result = append(result, v)
|
||||
}
|
||||
}
|
||||
@@ -797,23 +839,51 @@ func Without[T comparable](slice []T, values ...T) []T {
|
||||
return result
|
||||
}
|
||||
|
||||
// IndexOf returns the index at which the first occurrence of a value is found in a slice or return -1
|
||||
// if the value cannot be found.
|
||||
func IndexOf[T comparable](slice []T, value T) int {
|
||||
for i, v := range slice {
|
||||
if v == value {
|
||||
return i
|
||||
// IndexOf returns the index at which the first occurrence of an item is found in a slice or return -1 if the item cannot be found.
|
||||
func IndexOf[T comparable](arr []T, val T) int {
|
||||
limit := 10
|
||||
// gets the hash value of the array as the key of the hash table.
|
||||
key := fmt.Sprintf("%p", arr)
|
||||
// determines whether the hash table is empty. If so, the hash table is created.
|
||||
if memoryHashMap[key] == nil {
|
||||
memoryHashMap[key] = make(map[any]int)
|
||||
// iterate through the array, adding the value and index of each element to the hash table.
|
||||
for i := len(arr) - 1; i >= 0; i-- {
|
||||
memoryHashMap[key][arr[i]] = i
|
||||
}
|
||||
}
|
||||
// update the hash table counter.
|
||||
memoryHashCounter[key]++
|
||||
|
||||
// use the hash table to find the specified value. If found, the index is returned.
|
||||
if index, ok := memoryHashMap[key][val]; ok {
|
||||
// calculate the memory usage of the hash table.
|
||||
size := len(memoryHashMap)
|
||||
// If the memory usage of the hash table exceeds the memory limit, the hash table with the lowest counter is cleared.
|
||||
if size > limit {
|
||||
var minKey string
|
||||
var minVal int
|
||||
for k, v := range memoryHashCounter {
|
||||
if k == key {
|
||||
continue
|
||||
}
|
||||
if minVal == 0 || v < minVal {
|
||||
minKey = k
|
||||
minVal = v
|
||||
}
|
||||
}
|
||||
delete(memoryHashMap, minKey)
|
||||
delete(memoryHashCounter, minKey)
|
||||
}
|
||||
return index
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// LastIndexOf returns the index at which the last occurrence of a value is found in a slice or return -1
|
||||
// if the value cannot be found.
|
||||
func LastIndexOf[T comparable](slice []T, value T) int {
|
||||
// LastIndexOf returns the index at which the last occurrence of the item is found in a slice or return -1 if the then cannot be found.
|
||||
func LastIndexOf[T comparable](slice []T, item T) int {
|
||||
for i := len(slice) - 1; i > 0; i-- {
|
||||
if value == slice[i] {
|
||||
if item == slice[i] {
|
||||
return i
|
||||
}
|
||||
}
|
||||
@@ -822,27 +892,27 @@ func LastIndexOf[T comparable](slice []T, value T) int {
|
||||
}
|
||||
|
||||
// ToSlicePointer returns a pointer to the slices of a variable parameter transformation
|
||||
func ToSlicePointer[T any](value ...T) []*T {
|
||||
result := make([]*T, len(value))
|
||||
for i := range value {
|
||||
result[i] = &value[i]
|
||||
func ToSlicePointer[T any](items ...T) []*T {
|
||||
result := make([]*T, len(items))
|
||||
for i := range items {
|
||||
result[i] = &items[i]
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// ToSlice returns a slices of a variable parameter transformation
|
||||
func ToSlice[T any](value ...T) []T {
|
||||
result := make([]T, len(value))
|
||||
copy(result, value)
|
||||
func ToSlice[T any](items ...T) []T {
|
||||
result := make([]T, len(items))
|
||||
copy(result, items)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// AppendIfAbsent only absent append the value
|
||||
func AppendIfAbsent[T comparable](slice []T, value T) []T {
|
||||
if !Contain(slice, value) {
|
||||
slice = append(slice, value)
|
||||
// AppendIfAbsent only absent append the item
|
||||
func AppendIfAbsent[T comparable](slice []T, item T) []T {
|
||||
if !Contain(slice, item) {
|
||||
slice = append(slice, item)
|
||||
}
|
||||
return slice
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package slice
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"github.com/duke-git/lancet/v2/lancetconstraints"
|
||||
)
|
||||
|
||||
// sliceValue return the reflect value of a slice
|
||||
@@ -24,3 +26,66 @@ func sliceElemType(reflectType reflect.Type) reflect.Type {
|
||||
reflectType = reflectType.Elem()
|
||||
}
|
||||
}
|
||||
|
||||
func quickSort[T lancetconstraints.Ordered](slice []T, lowIndex, highIndex int, order string) {
|
||||
if lowIndex < highIndex {
|
||||
p := partitionOrderedSlice(slice, lowIndex, highIndex, order)
|
||||
quickSort(slice, lowIndex, p-1, order)
|
||||
quickSort(slice, p+1, highIndex, order)
|
||||
}
|
||||
}
|
||||
|
||||
// partitionOrderedSlice split ordered slice into two parts for quick sort
|
||||
func partitionOrderedSlice[T lancetconstraints.Ordered](slice []T, lowIndex, highIndex int, order string) int {
|
||||
p := slice[highIndex]
|
||||
i := lowIndex
|
||||
|
||||
for j := lowIndex; j < highIndex; j++ {
|
||||
if order == "desc" {
|
||||
if slice[j] > p {
|
||||
swap(slice, i, j)
|
||||
i++
|
||||
}
|
||||
} else {
|
||||
if slice[j] < p {
|
||||
swap(slice, i, j)
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
swap(slice, i, highIndex)
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
func quickSortBy[T any](slice []T, lowIndex, highIndex int, less func(a, b T) bool) {
|
||||
if lowIndex < highIndex {
|
||||
p := partitionAnySlice(slice, lowIndex, highIndex, less)
|
||||
quickSortBy(slice, lowIndex, p-1, less)
|
||||
quickSortBy(slice, p+1, highIndex, less)
|
||||
}
|
||||
}
|
||||
|
||||
// partitionAnySlice split any slice into two parts for quick sort
|
||||
func partitionAnySlice[T any](slice []T, lowIndex, highIndex int, less func(a, b T) bool) int {
|
||||
p := slice[highIndex]
|
||||
i := lowIndex
|
||||
|
||||
for j := lowIndex; j < highIndex; j++ {
|
||||
|
||||
if less(slice[j], p) {
|
||||
swap(slice, i, j)
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
swap(slice, i, highIndex)
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
// swap two slice value at index i and j
|
||||
func swap[T any](slice []T, i, j int) {
|
||||
slice[i], slice[j] = slice[j], slice[i]
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package slice
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
@@ -31,6 +32,10 @@ func TestChunk(t *testing.T) {
|
||||
|
||||
arr := []string{"a", "b", "c", "d", "e"}
|
||||
|
||||
assert.Equal([][]string{}, Chunk(arr, -1))
|
||||
|
||||
assert.Equal([][]string{}, Chunk(arr, 0))
|
||||
|
||||
r1 := [][]string{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}}
|
||||
assert.Equal(r1, Chunk(arr, 1))
|
||||
|
||||
@@ -43,8 +48,11 @@ func TestChunk(t *testing.T) {
|
||||
r4 := [][]string{{"a", "b", "c", "d"}, {"e"}}
|
||||
assert.Equal(r4, Chunk(arr, 4))
|
||||
|
||||
r5 := [][]string{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}}
|
||||
r5 := [][]string{{"a", "b", "c", "d", "e"}}
|
||||
assert.Equal(r5, Chunk(arr, 5))
|
||||
|
||||
r6 := [][]string{{"a", "b", "c", "d", "e"}}
|
||||
assert.Equal(r6, Chunk(arr, 6))
|
||||
}
|
||||
|
||||
func TestCompact(t *testing.T) {
|
||||
@@ -186,13 +194,22 @@ func TestGroupWith(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCount(t *testing.T) {
|
||||
numbers := []int{1, 2, 3, 3, 5, 6}
|
||||
|
||||
assert := internal.NewAssert(t, "TestCountBy")
|
||||
|
||||
assert.Equal(1, Count(numbers, 1))
|
||||
assert.Equal(2, Count(numbers, 3))
|
||||
}
|
||||
|
||||
func TestCountBy(t *testing.T) {
|
||||
nums := []int{1, 2, 3, 4, 5, 6}
|
||||
evenFunc := func(i, num int) bool {
|
||||
return (num % 2) == 0
|
||||
}
|
||||
|
||||
assert := internal.NewAssert(t, "TestCount")
|
||||
assert.Equal(3, Count(nums, evenFunc))
|
||||
assert := internal.NewAssert(t, "TestCountBy")
|
||||
assert.Equal(3, CountBy(nums, evenFunc))
|
||||
}
|
||||
|
||||
func TestFind(t *testing.T) {
|
||||
@@ -439,6 +456,18 @@ func TestUnionBy(t *testing.T) {
|
||||
assert.Equal(result, []int{0, 2, 4, 10})
|
||||
}
|
||||
|
||||
func TestMerge(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestMerge")
|
||||
|
||||
s1 := []int{1, 2, 3, 4}
|
||||
s2 := []int{2, 3, 4, 5}
|
||||
s3 := []int{4, 5, 6}
|
||||
|
||||
assert.Equal([]int{1, 2, 3, 4, 2, 3, 4, 5, 4, 5, 6}, Merge(s1, s2, s3))
|
||||
assert.Equal([]int{1, 2, 3, 4, 2, 3, 4, 5}, Merge(s1, s2))
|
||||
assert.Equal([]int{2, 3, 4, 5, 4, 5, 6}, Merge(s2, s3))
|
||||
}
|
||||
|
||||
func TestIntersection(t *testing.T) {
|
||||
s1 := []int{1, 2, 2, 3}
|
||||
s2 := []int{1, 2, 3, 4}
|
||||
@@ -519,6 +548,56 @@ func TestDifferenceBy(t *testing.T) {
|
||||
assert.Equal([]int{1, 2}, DifferenceBy(s1, s2, addOne))
|
||||
}
|
||||
|
||||
func TestSort(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSort")
|
||||
|
||||
numbers := []int{1, 4, 3, 2, 5}
|
||||
|
||||
Sort(numbers)
|
||||
assert.Equal([]int{1, 2, 3, 4, 5}, numbers)
|
||||
|
||||
Sort(numbers, "desc")
|
||||
assert.Equal([]int{5, 4, 3, 2, 1}, numbers)
|
||||
|
||||
strings := []string{"a", "d", "c", "b", "e"}
|
||||
|
||||
Sort(strings)
|
||||
assert.Equal([]string{"a", "b", "c", "d", "e"}, strings)
|
||||
|
||||
Sort(strings, "desc")
|
||||
assert.Equal([]string{"e", "d", "c", "b", "a"}, strings)
|
||||
}
|
||||
|
||||
func TestSortBy(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSortBy")
|
||||
|
||||
numbers := []int{1, 4, 3, 2, 5}
|
||||
|
||||
SortBy(numbers, func(a, b int) bool {
|
||||
return a < b
|
||||
})
|
||||
assert.Equal([]int{1, 2, 3, 4, 5}, numbers)
|
||||
|
||||
type User struct {
|
||||
Name string
|
||||
Age uint
|
||||
}
|
||||
|
||||
users := []User{
|
||||
{Name: "a", Age: 21},
|
||||
{Name: "b", Age: 15},
|
||||
{Name: "c", Age: 100}}
|
||||
|
||||
SortBy(users, func(a, b User) bool {
|
||||
return a.Age < b.Age
|
||||
})
|
||||
|
||||
t.Logf("sort users by age: %v", users)
|
||||
|
||||
// output
|
||||
// [{b 15} {a 21} {c 100}]
|
||||
}
|
||||
|
||||
func TestSortByFielDesc(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSortByFielDesc")
|
||||
|
||||
@@ -591,8 +670,39 @@ func TestIndexOf(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestIndexOf")
|
||||
|
||||
arr := []string{"a", "a", "b", "c"}
|
||||
key := fmt.Sprintf("%p", arr)
|
||||
assert.Equal(0, IndexOf(arr, "a"))
|
||||
assert.Equal(-1, IndexOf(arr, "d"))
|
||||
assert.Equal(2, memoryHashCounter[key])
|
||||
|
||||
arr1 := []int{1, 2, 3, 4, 5}
|
||||
key1 := fmt.Sprintf("%p", arr1)
|
||||
assert.Equal(3, IndexOf(arr1, 4))
|
||||
assert.Equal(-1, IndexOf(arr1, 6))
|
||||
assert.Equal(2, memoryHashCounter[key1])
|
||||
|
||||
arr2 := []float64{1.1, 2.2, 3.3, 4.4, 5.5}
|
||||
key2 := fmt.Sprintf("%p", arr2)
|
||||
assert.Equal(2, IndexOf(arr2, 3.3))
|
||||
assert.Equal(3, IndexOf(arr2, 4.4))
|
||||
assert.Equal(-1, IndexOf(arr2, 6.6))
|
||||
assert.Equal(3, memoryHashCounter[key2])
|
||||
|
||||
for i := 0; i < 6; i++ {
|
||||
a := []string{"a", "b", "c"}
|
||||
IndexOf(a, "a")
|
||||
IndexOf(a, "b")
|
||||
}
|
||||
minArr := []string{"c", "b", "a"}
|
||||
minKey := fmt.Sprintf("%p", minArr)
|
||||
assert.Equal(0, IndexOf(minArr, "c"))
|
||||
|
||||
arr3 := []string{"q", "w", "e"}
|
||||
key3 := fmt.Sprintf("%p", arr3)
|
||||
assert.Equal(1, IndexOf(arr3, "w"))
|
||||
assert.Equal(-1, IndexOf(arr3, "r"))
|
||||
assert.Equal(2, memoryHashCounter[key3])
|
||||
assert.Equal(0, memoryHashCounter[minKey])
|
||||
}
|
||||
|
||||
func TestLastIndexOf(t *testing.T) {
|
||||
@@ -665,3 +775,11 @@ func TestKeyBy(t *testing.T) {
|
||||
|
||||
assert.Equal(result, map[int]string{1: "a", 2: "ab", 3: "abc"})
|
||||
}
|
||||
|
||||
func TestRepeat(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestRepeat")
|
||||
|
||||
result := Repeat("a", 6)
|
||||
|
||||
assert.Equal(result, []string{"a", "a", "a", "a", "a", "a"})
|
||||
}
|
||||
|
||||
50
system/os.go
50
system/os.go
@@ -9,6 +9,10 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/duke-git/lancet/v2/validator"
|
||||
"golang.org/x/text/encoding/simplifiedchinese"
|
||||
)
|
||||
|
||||
// IsWindows check if current os is windows
|
||||
@@ -50,27 +54,61 @@ func CompareOsEnv(key, comparedEnv string) bool {
|
||||
return env == comparedEnv
|
||||
}
|
||||
|
||||
// ExecCommand use shell /bin/bash -c to execute command
|
||||
// ExecCommand execute command, return the stdout and stderr string of command, and error if error occur
|
||||
// param `command` is a complete command string, like, ls -a (linux), dir(windows), ping 127.0.0.1
|
||||
// in linux, use /bin/bash -c to execute command
|
||||
// in windows, use powershell.exe to execute command
|
||||
func ExecCommand(command string) (stdout, stderr string, err error) {
|
||||
var out bytes.Buffer
|
||||
var errout bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
|
||||
cmd := exec.Command("/bin/bash", "-c", command)
|
||||
if IsWindows() {
|
||||
cmd = exec.Command("cmd")
|
||||
cmd = exec.Command("powershell.exe", command)
|
||||
}
|
||||
cmd.Stdout = &out
|
||||
cmd.Stderr = &errout
|
||||
cmd.Stderr = &errOut
|
||||
|
||||
err = cmd.Run()
|
||||
|
||||
if err != nil {
|
||||
stderr = string(errout.Bytes())
|
||||
if utf8.Valid(errOut.Bytes()) {
|
||||
stderr = byteToString(errOut.Bytes(), "UTF8")
|
||||
} else if validator.IsGBK(errOut.Bytes()) {
|
||||
stderr = byteToString(errOut.Bytes(), "GBK")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
data := out.Bytes()
|
||||
if utf8.Valid(data) {
|
||||
stdout = byteToString(data, "UTF8")
|
||||
} else if validator.IsGBK(data) {
|
||||
stdout = byteToString(data, "GBK")
|
||||
}
|
||||
stdout = string(out.Bytes())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func byteToString(data []byte, charset string) string {
|
||||
var result string
|
||||
|
||||
switch charset {
|
||||
case "GBK":
|
||||
decodeBytes, _ := simplifiedchinese.GBK.NewDecoder().Bytes(data)
|
||||
result = string(decodeBytes)
|
||||
case "GB18030":
|
||||
decodeBytes, _ := simplifiedchinese.GB18030.NewDecoder().Bytes(data)
|
||||
result = string(decodeBytes)
|
||||
case "UTF8":
|
||||
fallthrough
|
||||
default:
|
||||
result = string(data)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GetOsBits get this system bits 32bit or 64bit
|
||||
// return bit int (32/64)
|
||||
func GetOsBits() int {
|
||||
|
||||
@@ -11,10 +11,10 @@ func TestOsDetection(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestOsJudgment")
|
||||
|
||||
osType, _, _ := ExecCommand("echo $OSTYPE")
|
||||
if strings.Index(osType, "linux") != -1 {
|
||||
if strings.Contains(osType, "linux") {
|
||||
assert.Equal(true, IsLinux())
|
||||
}
|
||||
if strings.Index(osType, "darwin") != -1 {
|
||||
if strings.Contains(osType, "darwin") {
|
||||
assert.Equal(true, IsMac())
|
||||
}
|
||||
}
|
||||
@@ -44,21 +44,27 @@ func TestOsEnvOperation(t *testing.T) {
|
||||
func TestExecCommand(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestExecCommand")
|
||||
|
||||
out, errout, err := ExecCommand("ls")
|
||||
t.Log("std out: ", out)
|
||||
t.Log("std err: ", errout)
|
||||
// linux or mac
|
||||
stdout, stderr, err := ExecCommand("ls")
|
||||
t.Log("std out: ", stdout)
|
||||
t.Log("std err: ", stderr)
|
||||
assert.Equal("", stderr)
|
||||
assert.IsNil(err)
|
||||
|
||||
out, errout, err = ExecCommand("abc")
|
||||
t.Log("std out: ", out)
|
||||
t.Log("std err: ", errout)
|
||||
if err != nil {
|
||||
t.Logf("error: %v\n", err)
|
||||
}
|
||||
// windows
|
||||
stdout, stderr, err = ExecCommand("dir")
|
||||
t.Log("std out: ", stdout)
|
||||
t.Log("std err: ", stderr)
|
||||
assert.IsNil(err)
|
||||
|
||||
if !IsWindows() {
|
||||
assert.IsNotNil(err)
|
||||
}
|
||||
// error command
|
||||
stdout, stderr, err = ExecCommand("abc")
|
||||
t.Log("std out: ", stdout)
|
||||
t.Log("std err: ", stderr)
|
||||
// if err != nil {
|
||||
// t.Log(err.Error())
|
||||
// }
|
||||
assert.IsNotNil(err)
|
||||
}
|
||||
|
||||
func TestGetOsBits(t *testing.T) {
|
||||
|
||||
@@ -15,11 +15,24 @@ import (
|
||||
"unicode"
|
||||
)
|
||||
|
||||
var isAlphaRegexMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z]+$`)
|
||||
var (
|
||||
alphaMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z]+$`)
|
||||
letterRegexMatcher *regexp.Regexp = regexp.MustCompile(`[a-zA-Z]`)
|
||||
intStrMatcher *regexp.Regexp = regexp.MustCompile(`^[\+-]?\d+$`)
|
||||
urlMatcher *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]*)?$`)
|
||||
dnsMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z]([a-zA-Z0-9\-]+[\.]?)*[a-zA-Z0-9]$`)
|
||||
emailMatcher *regexp.Regexp = regexp.MustCompile(`\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*`)
|
||||
chineseMobileMatcher *regexp.Regexp = regexp.MustCompile(`^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$`)
|
||||
chineseIdMatcher *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]$`)
|
||||
chineseMatcher *regexp.Regexp = regexp.MustCompile("[\u4e00-\u9fa5]")
|
||||
chinesePhoneMatcher *regexp.Regexp = regexp.MustCompile(`\d{3}-\d{8}|\d{4}-\d{7}`)
|
||||
creditCardMatcher *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})$`)
|
||||
base64Matcher *regexp.Regexp = regexp.MustCompile(`^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$`)
|
||||
)
|
||||
|
||||
// IsAlpha checks if the string contains only letters (a-zA-Z)
|
||||
func IsAlpha(str string) bool {
|
||||
return isAlphaRegexMatcher.MatchString(str)
|
||||
return alphaMatcher.MatchString(str)
|
||||
}
|
||||
|
||||
// IsAllUpper check if the string is all upper case letters A-Z
|
||||
@@ -62,11 +75,9 @@ func ContainLower(str string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
var containLetterRegexMatcher *regexp.Regexp = regexp.MustCompile(`[a-zA-Z]`)
|
||||
|
||||
// ContainLetter check if the string contain at least one letter
|
||||
func ContainLetter(str string) bool {
|
||||
return containLetterRegexMatcher.MatchString(str)
|
||||
return letterRegexMatcher.MatchString(str)
|
||||
}
|
||||
|
||||
// IsJSON checks if the string is valid JSON
|
||||
@@ -86,11 +97,9 @@ func IsFloatStr(str string) bool {
|
||||
return e == nil
|
||||
}
|
||||
|
||||
var isIntStrRegexMatcher *regexp.Regexp = regexp.MustCompile(`^[\+-]?\d+$`)
|
||||
|
||||
// IsIntStr check if the string can convert to a integer.
|
||||
func IsIntStr(str string) bool {
|
||||
return isIntStrRegexMatcher.MatchString(str)
|
||||
return intStrMatcher.MatchString(str)
|
||||
}
|
||||
|
||||
// IsIp check if the string is a ip address.
|
||||
@@ -125,8 +134,6 @@ 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, ".") {
|
||||
@@ -143,64 +150,48 @@ func IsUrl(str string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
return isUrlRegexMatcher.MatchString(str)
|
||||
return urlMatcher.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.
|
||||
func IsDns(dns string) bool {
|
||||
return isDnsRegexMatcher.MatchString(dns)
|
||||
return dnsMatcher.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 {
|
||||
return isEmailRegexMatcher.MatchString(email)
|
||||
return emailMatcher.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 {
|
||||
return isChineseMobileRegexMatcher.MatchString(mobileNum)
|
||||
return chineseMobileMatcher.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 {
|
||||
return isChineseIdNumRegexMatcher.MatchString(id)
|
||||
return chineseIdMatcher.MatchString(id)
|
||||
}
|
||||
|
||||
var containChineseRegexMatcher *regexp.Regexp = regexp.MustCompile("[\u4e00-\u9fa5]")
|
||||
|
||||
// ContainChinese check if the string contain mandarin chinese.
|
||||
func ContainChinese(s string) bool {
|
||||
return containChineseRegexMatcher.MatchString(s)
|
||||
return chineseMatcher.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 {
|
||||
return isChinesePhoneRegexMatcher.MatchString(phone)
|
||||
return chinesePhoneMatcher.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 {
|
||||
return isCreditCardRegexMatcher.MatchString(creditCart)
|
||||
return creditCardMatcher.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 {
|
||||
return isBase64RegexMatcher.MatchString(base64)
|
||||
return base64Matcher.MatchString(base64)
|
||||
}
|
||||
|
||||
// IsEmptyString check if the string is empty.
|
||||
@@ -283,3 +274,40 @@ func IsZeroValue(value any) bool {
|
||||
|
||||
return reflect.DeepEqual(rv.Interface(), reflect.Zero(rv.Type()).Interface())
|
||||
}
|
||||
|
||||
// IsGBK check if data encoding is gbk
|
||||
// Note: this function is implemented by whether double bytes fall within the encoding range of gbk,
|
||||
// while each byte of utf-8 encoding format falls within the encoding range of gbk.
|
||||
// Therefore, utf8.valid() should be called first to check whether it is not utf-8 encoding,
|
||||
// and then call IsGBK() to check gbk encoding. like below
|
||||
/**
|
||||
data := []byte("你好")
|
||||
if utf8.Valid(data) {
|
||||
fmt.Println("data encoding is utf-8")
|
||||
}else if(IsGBK(data)) {
|
||||
fmt.Println("data encoding is GBK")
|
||||
}
|
||||
fmt.Println("data encoding is unknown")
|
||||
**/
|
||||
func IsGBK(data []byte) bool {
|
||||
i := 0
|
||||
for i < len(data) {
|
||||
if data[i] <= 0xff {
|
||||
i++
|
||||
continue
|
||||
} else {
|
||||
if data[i] >= 0x81 &&
|
||||
data[i] <= 0xfe &&
|
||||
data[i+1] >= 0x40 &&
|
||||
data[i+1] <= 0xfe &&
|
||||
data[i+1] != 0xf7 {
|
||||
i += 2
|
||||
continue
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/duke-git/lancet/v2/internal"
|
||||
"golang.org/x/text/encoding/simplifiedchinese"
|
||||
)
|
||||
|
||||
func TestIsAllUpper(t *testing.T) {
|
||||
@@ -388,3 +390,13 @@ func TestIsZeroValue(t *testing.T) {
|
||||
assert.Equal(false, IsZeroValue(value))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsGBK(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestIsGBK")
|
||||
|
||||
str := "你好"
|
||||
gbkData, _ := simplifiedchinese.GBK.NewEncoder().Bytes([]byte(str))
|
||||
|
||||
assert.Equal(true, IsGBK(gbkData))
|
||||
assert.Equal(false, utf8.Valid(gbkData))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user