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

Compare commits

...

138 Commits

Author SHA1 Message Date
dudaodong
3beb769f09 release v2.2.0 2023-05-18 10:53:02 +08:00
dudaodong
8af02ff95b doc: update readme file 2023-05-18 10:51:33 +08:00
dudaodong
ba4485d8c0 merge main 2023-05-18 10:32:36 +08:00
dudaodong
8a1dd40738 doc: add doc for AddYear function 2023-05-18 10:27:37 +08:00
dudaodong
85e2806531 doc: add doc for FindLast 2023-05-18 10:21:24 +08:00
will
1616d3d1be feat:addFindLast for stream (#95)
Co-authored-by: sunyaoyao <sunyaoyao@kezaihui.com>
2023-05-18 10:17:15 +08:00
tlei995
aa8e0d5c12 feat:add AddYear func (#96)
Co-authored-by: leitao <leitao@kezaihui.com>
2023-05-18 10:14:23 +08:00
dudaodong
f05477d9cf fix: update logic of Percent function 2023-05-18 10:11:48 +08:00
dudaodong
cd91e16b26 doc: update document for strutil and convertor package 2023-05-11 10:06:32 +08:00
dudaodong
9fcf046fb3 feat: add Trim and SplitAndTrim 2023-05-10 10:53:17 +08:00
dudaodong
c3f1bc39d7 feat: add ReplaceWithMap 2023-05-10 10:29:26 +08:00
dudaodong
f5784b0f46 feat: add ReplaceByMap 2023-05-10 10:03:13 +08:00
dudaodong
c86a8a479d feat: add ToInterface 2023-05-09 12:01:57 +08:00
dudaodong
e2aeb8ec07 doc: add document for GCD and LCM function 2023-05-06 11:28:38 +08:00
dudaodong
654ba15aaf feat: add GCD and LCM function 2023-05-06 11:02:00 +08:00
dudaodong
945c59896b feat: add IsLeapYear 2023-04-28 14:42:25 +08:00
dudaodong
219e31d929 fix: fix format issue 2023-04-27 15:49:58 +08:00
dudaodong
82cb86b35c doc: add go playground demo for compare package 2023-04-27 14:15:25 +08:00
dudaodong
f93c561f5d doc: update go playground demo 2023-04-27 12:03:15 +08:00
dudaodong
4888909208 fix: fix IsPingConnected failed in windows 2023-04-26 19:53:53 +08:00
dudaodong
33c8875d14 test: update TestWordCount 2023-04-26 19:35:28 +08:00
dudaodong
99cb1b13a3 test: remove unstable test item 2023-04-26 18:14:27 +08:00
dudaodong
42ec189995 release v2.1.20 2023-04-26 18:03:52 +08:00
dudaodong
424c291813 test: add TestExecCommandWithOption 2023-04-26 17:53:20 +08:00
dudaodong
4311b9ac66 test: remove t.Log() 2023-04-26 14:59:45 +08:00
dudaodong
581e338889 doc: add new function to readme file 2023-04-26 14:31:47 +08:00
dudaodong
f399425c2a doc: add document for compare package 2023-04-26 11:02:11 +08:00
dudaodong
dcdb29334d doc: update fileutils package document 2023-04-26 10:44:12 +08:00
dudaodong
4859f3ca23 test: add examples for compare package 2023-04-26 10:19:42 +08:00
dudaodong
9f2528842e feat: add unit test for compare package 2023-04-26 10:05:09 +08:00
dudaodong
6066d6669f feat: add compare package 2023-04-25 18:01:05 +08:00
dudaodong
e3804e9534 test: add test.csv file 2023-04-25 11:34:09 +08:00
dudaodong
2f51397d2c feat: add ReadCsvFile 2023-04-25 11:28:43 +08:00
dudaodong
11217a11c7 feat: add FileSize, MTime, Sha 2023-04-25 11:16:00 +08:00
dudaodong
fa81ee143e refactor: update param name CopyFile 2023-04-25 10:49:12 +08:00
dudaodong
62891f20f8 feat: add IsZipFile 2023-04-24 14:00:53 +08:00
dudaodong
5e79eaa9dd feat: add IsZipFile 2023-04-24 11:00:58 +08:00
dudaodong
aaf45012e4 fix: refact CopyProperties 2023-04-22 14:14:13 +08:00
dudaodong
48c17ea1ce fix: update params in TestIsPingConnected 2023-04-19 17:40:55 +08:00
dudaodong
e90283c3f9 fix: update params in TestIsPingConnected 2023-04-19 17:35:17 +08:00
dudaodong
f82c4a305d fix: update params in TestIsPingConnected 2023-04-19 17:32:30 +08:00
dudaodong
05997603a9 doc: add document for DownloadFile and UploadFile 2023-04-19 16:16:47 +08:00
dudaodong
6d5ec807f7 test: comment some test case 2023-04-19 16:04:35 +08:00
dudaodong
f73c7e7e86 doc: add document and example for IsPingConnected and IsTelnetConnected 2023-04-19 11:48:28 +08:00
dudaodong
c137428b9e feat: add IsPingConnected and IsTelnetConnected 2023-04-19 11:14:10 +08:00
dudaodong
9f68620b37 feat: add IsPingConnected and IsTelnetConnected 2023-04-19 11:13:21 +08:00
dudaodong
2cdbba56a4 feat: add UploadFile and DownloadFile 2023-04-18 20:09:56 +08:00
dudaodong
01a3b139c0 doc: add document for new functions in slice and strutil package 2023-04-18 15:49:09 +08:00
dudaodong
fcb3b97b45 doc: add docment and playground demo for v2.1.19 2023-04-18 15:21:03 +08:00
dudaodong
52ea64bc33 feat: add FindLastBy function 2023-04-17 20:17:26 +08:00
燕归来
14bc08c6d6 feat: add FindBy that a result will be without unrefrence #88 (#90)
feat: add example for FindBy

chore: reduce code duplication
2023-04-17 20:11:56 +08:00
dudaodong
47bdd6718a fix: ExecCommand can't compile in macos 2023-04-17 17:03:46 +08:00
dudaodong
18d27604e6 update mod file 2023-04-17 17:00:53 +08:00
dudaodong
66bd339e3a doc: add example for strutil new functions 2023-04-17 16:35:26 +08:00
燕归来
04abb7a3ea feat: add some function for strutil package #88 (#89) 2023-04-17 16:07:14 +08:00
dudaodong
975c303a31 fix: ExampleListFileNames 2023-04-17 15:35:17 +08:00
dudaodong
3b8dd94a5c fix: TestListFileNames 2023-04-17 15:32:59 +08:00
dudaodong
815791c0b6 Merge branch 'main' into v2 2023-04-17 15:28:37 +08:00
dudaodong
a12a691ee6 release v2.1.19 2023-04-17 15:28:01 +08:00
Nothin
247cf89947 [FEATURE] system add option (#87) 2023-04-17 14:06:49 +08:00
dudaodong
c3fad62d8c doc: update stream package document 2023-04-17 13:53:47 +08:00
dudaodong
a8a96be21b doc: update doc for new added functions 2023-04-17 11:34:17 +08:00
dudaodong
8e297769b2 fix: fix example comment of MapTo function 2023-04-17 11:06:03 +08:00
dudaodong
98cdf1c040 Merge branch 'main' into v2 2023-04-17 10:38:28 +08:00
dudaodong
d7976e31a4 refactor: move typemap.go to maputil package and add document for it 2023-04-17 10:37:56 +08:00
dudaodong
5b11a8b457 refactor: move typemap.go to maputil package and add document for it 2023-04-17 10:36:59 +08:00
Nothin
d4a16534f2 add typemap (#85)
* [FEATURE] typemap, quick map any type to specified type

* [DOC] add more test case

---------

Co-authored-by: zhijian.chen <zhijian.chen@longsys.com>
2023-04-17 10:04:31 +08:00
dudaodong
ecf0688788 update readme file 2023-04-07 17:39:54 +08:00
dudaodong
90f9cad1ea update readme file 2023-04-07 15:23:34 +08:00
dudaodong
4a298876e9 doc: add docment and example for byte.go 2023-04-07 14:53:48 +08:00
dudaodong
74474cd9ef feat: add feature for humanize byte unit 2023-04-07 14:18:28 +08:00
dudaodong
f23f18457e feat: add Pretty and PrettyToWriter 2023-04-06 16:30:38 +08:00
dudaodong
18f01ffd75 doc: update doc and example for validator 2023-04-06 10:46:31 +08:00
dudaodong
c53d541a6b doc: add document for stream package 2023-04-05 20:17:41 +08:00
dudaodong
5b9b4c4344 test: add example for stream package 2023-04-05 18:52:27 +08:00
dudaodong
6e7300bbbf feat: add CurrentPath 2023-04-05 15:55:55 +08:00
dudaodong
3685aee02b fix: fix bug of Comma function 2023-04-05 14:26:42 +08:00
dudaodong
046f3e0bf9 feat: add IsInt, IsFloat, IsNumber 2023-04-05 14:07:23 +08:00
dudaodong
c01c9d14b4 feat: add ReduceRight 2023-04-04 17:54:54 +08:00
dudaodong
f198191063 feat: add ReduceBy 2023-04-04 17:41:37 +08:00
dudaodong
8bdd46bda4 doc: add play ground demo 2023-04-03 10:33:57 +08:00
dudaodong
e29b56c3c3 release v2.1.18 2023-04-03 10:12:50 +08:00
dudaodong
c357fc68c8 doc: update readme file for new feature 2023-04-03 10:12:13 +08:00
dudaodong
bc25e7a037 feat: add IsPrintable 2023-03-31 12:00:32 +08:00
dudaodong
217350042b feat: add RemoveNonPrintable 2023-03-30 14:52:32 +08:00
dudaodong
e56a8a1ef5 feat: add IsASCII 2023-03-30 14:41:32 +08:00
dudaodong
6453f755a6 doc: add doc for IsPrime 2023-03-30 14:09:05 +08:00
dudaodong
027abd6ad5 feat: add IsPrime 2023-03-30 11:54:20 +08:00
dudaodong
91503b1656 comment TestEachWithBreak 2023-03-29 10:31:38 +08:00
dudaodong
e2522cd29b fix: fix TestEachWithBreak case 2023-03-29 10:24:41 +08:00
dudaodong
da69b77892 Merge branch 'main' of github.com:duke-git/lancet 2023-03-29 10:15:56 +08:00
dudaodong
05772d8d7d comment TestEachWithBreak 2023-03-28 20:08:05 +08:00
Mickls
3b497532f3 fix: The LastIndexOf method can never return the index of the first element (#83)
Co-authored-by: JiangCheng <jiangcheng@kezaihui.com>
2023-03-28 20:02:57 +08:00
dudaodong
1cd3be508c refactor rename async package name to 2023-03-24 11:43:56 +08:00
dudaodong
a41d461910 doc: update mathutil package doc 2023-03-24 11:23:45 +08:00
dudaodong
cde5946bf0 feat: add PointDistance 2023-03-23 17:49:07 +08:00
dudaodong
c28803b25e feat: add AngleToRadian and RadianToAngle 2023-03-23 17:41:31 +08:00
dudaodong
f09e521783 doc: add go playground demo 2023-03-22 21:06:01 +08:00
dudaodong
0aa41f337d fix: test failed 2023-03-20 16:39:56 +08:00
dudaodong
48814a720a fix: test failed in promise test 2023-03-20 16:26:21 +08:00
dudaodong
04b79b3dfe release v2.1.17 2023-03-20 16:17:52 +08:00
dudaodong
302007ebdf doc: update readme file for new feature 2023-03-20 16:12:58 +08:00
dudaodong
965e5fbcda feat: add Pop for set 2023-03-20 11:10:35 +08:00
dudaodong
70d0adde42 feat: add EachWithBreak for set 2023-03-20 10:49:14 +08:00
dudaodong
0b80074bb7 refactor: remove unused code 2023-03-20 10:35:37 +08:00
dudaodong
90945a0399 Merge branch 'main' into v2 2023-03-18 19:35:48 +08:00
zm
47dccd63af add the struct package english docs (#82) 2023-03-18 19:33:07 +08:00
dudaodong
4ae7e59829 feat: add example for promise 2023-03-17 16:03:35 +08:00
dudaodong
8f0c60cade test: add unit test for promise Race and Any function 2023-03-17 13:59:18 +08:00
dudaodong
3f6aef1432 fix: fix bug of IsNotNil function 2023-03-16 19:15:36 +08:00
dudaodong
a714e04470 test: add unit test for promise.All function 2023-03-16 19:11:30 +08:00
dudaodong
7456621153 fix: fix bug of IsNil function 2023-03-16 17:01:28 +08:00
dudaodong
73ac9825e9 test: add unit test for Promise 2023-03-16 16:55:32 +08:00
dudaodong
930bb9c839 feat: complete promise Any function 2023-03-16 15:59:06 +08:00
dudaodong
3d8f1be212 feat: add error_join.go to support join error under go1.19, for internal use. 2023-03-16 15:56:54 +08:00
dudaodong
13a4ed59fa doc: update comment for concurrency package 2023-03-16 15:35:26 +08:00
dudaodong
c799d10ce9 feat: add promise All, Race, Any methods 2023-03-16 15:34:28 +08:00
dudaodong
5ab322ade2 feat: add async package, promise implemention 2023-03-16 14:49:07 +08:00
dudaodong
d0ffc61842 doc: fix doc error 2023-03-16 10:36:06 +08:00
zm
5e66bc6227 [structs] change package structutil to structs (#81)
* refactor package structutil to structs

* add structs package zh-CN docs
2023-03-15 19:14:19 +08:00
dudaodong
7261b281ad refactor: add function comment for tag.go 2023-03-15 17:43:47 +08:00
dudaodong
f79693804b refactor: make package variable defaultTagName unexported 2023-03-15 15:08:56 +08:00
dudaodong
534c7a0abc refactor: make errInvalidStruct exported, change error.go to struct_internal.go 2023-03-15 14:58:34 +08:00
dudaodong
4eaff47d38 Merge branch 'main' into v2 2023-03-15 14:43:48 +08:00
dudaodong
3e019522c7 doc: add doc for ForEachWithBreak 2023-03-15 14:42:22 +08:00
dudaodong
0734f220b3 feat: add ForEachWithBreak support break for each loop 2023-03-15 14:38:33 +08:00
zm
2d2c277090 [StructUtil] add support that the Struct can nest any type to transform (#80)
* add support json tag attribute for StructToMap function

* add the structutil to provide more rich functions and fixed #77

* add support that the nested struct to map for structutil

* recover code

* add structutil unit test

* [StructUtil] add unit test
2023-03-15 14:26:34 +08:00
dudaodong
ef1e548dfc merge main 2023-03-13 19:44:44 +08:00
zm
924589d2da Add StructUtil for provide more rich functions (#79)
* add support json tag attribute for StructToMap function

* add the structutil to provide more rich functions and fixed #77
2023-03-13 19:28:37 +08:00
dudaodong
77f32f4cc6 Merge branch 'main' into v2 2023-03-11 20:14:32 +08:00
zm
1755dd249b add support json tag attribute for StructToMap function (#78) 2023-03-11 20:08:41 +08:00
dudaodong
7a25688ec1 doc: add doc for Range and RangeWithStep 2023-03-09 17:13:51 +08:00
dudaodong
51a6912eb3 feat: add RangeWithStep function 2023-03-06 18:05:58 +08:00
dudaodong
28d0428b50 feat: add Range function 2023-03-06 17:49:56 +08:00
dudaodong
6a9eb645bb fix: fix StructToUrlValues failed when tag contain omitempty 2023-03-06 17:07:57 +08:00
dudaodong
3857b342f6 fix: fix ExampleContext failed 2023-03-01 11:45:02 +08:00
dudaodong
71aa91a58d doc: add go playground demo 2023-03-01 11:39:27 +08:00
dudaodong
081908bce3 fix: fix goline error 2023-03-01 11:10:12 +08:00
113 changed files with 14700 additions and 1400 deletions

3
.gitignore vendored
View File

@@ -7,4 +7,5 @@ fileutil/*.zip
fileutil/*.link
fileutil/unzip/*
slice/testdata/*
cryptor/*.pem
cryptor/*.pem
test

380
README.md
View File

@@ -4,7 +4,7 @@
<br/>
![Go version](https://img.shields.io/badge/go-%3E%3Dv1.18-9cf)
[![Release](https://img.shields.io/badge/release-2.1.16-green.svg)](https://github.com/duke-git/lancet/releases)
[![Release](https://img.shields.io/badge/release-2.2.0-green.svg)](https://github.com/duke-git/lancet/releases)
[![GoDoc](https://godoc.org/github.com/duke-git/lancet/v2?status.svg)](https://pkg.go.dev/github.com/duke-git/lancet/v2)
[![Go Report Card](https://goreportcard.com/badge/github.com/duke-git/lancet/v2)](https://goreportcard.com/report/github.com/duke-git/lancet/v2)
[![test](https://github.com/duke-git/lancet/actions/workflows/codecov.yml/badge.svg?branch=main&event=push)](https://github.com/duke-git/lancet/actions/workflows/codecov.yml)
@@ -24,7 +24,7 @@ English | [简体中文](./README_zh-CN.md)
## Feature
- 👏 Comprehensive, efficient and reusable.
- 💪 400+ go util functions, support string, slice, datetime, net, crypt...
- 💪 500+ go util functions, support string, slice, datetime, net, crypt...
- 💅 Only depend on the go standard library.
- 🌍 Unit test for every exported function.
@@ -38,10 +38,10 @@ English | [简体中文](./README_zh-CN.md)
go get github.com/duke-git/lancet/v2 // will install latest version of v2.x.x
```
2. <b>For users who use version below go1.18, you should install v1.x.x. The latest of v1.x.x is v1.3.7. </b>
2. <b>For users who use version below go1.18, you should install v1.x.x. The latest of v1.x.x is v1.3.8. </b>
```go
go get github.com/duke-git/lancet@v1.3.7 // below go1.18, install latest version of v1.x.x
go get github.com/duke-git/lancet // below go1.18, install latest version of v1.x.x
```
## Usage
@@ -118,7 +118,34 @@ import "github.com/duke-git/lancet/v2/algorithm"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/algorithm.md#LRUCache)]
[[play](https://go.dev/play/p/-EZjgOURufP)]
### 2. Concurrency package contain some functions to support concurrent programming. eg, goroutine, channel, async.
### 2. Compare package provides a lightweight comparison function on any type.
```go
import "github.com/duke-git/lancet/v2/compare"
```
#### Function list:
- **<big>Equal</big>** : Checks if two values are equal or not. (check both type and value)
[[doc](https://github.com/duke-git/lancet/blob/main/docs/compare.md#Equal)]
[[play](https://go.dev/play/p/wmVxR-to4lz)]
- **<big>EqualValue</big>** : Checks if two values are equal or not. (check value only)
[[doc](https://github.com/duke-git/lancet/blob/main/docs/compare.md#EqualValue)]
[[play](https://go.dev/play/p/fxnna_LLD9u)]
- **<big>LessThan</big>** : Checks if value `left` less than value `right`.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/compare.md#LessThan)]
[[play](https://go.dev/play/p/cYh7FQQj0ne)]
- **<big>GreaterThan</big>** : Checks if value `left` greater than value `right`.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/compare.md#GreaterThan)]
[[play](https://go.dev/play/p/9-NYDFZmIMp)]
- **<big>LessOrEqual</big>** : Checks if value `left` less than or equal than value `right`.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/compare.md#LessOrEqual)]
[[play](https://go.dev/play/p/e4T_scwoQzp)]
- **<big>GreaterOrEqual</big>** : Checks if value `left` less greater or equal than value `right`.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/compare.md#GreaterOrEqual)]
[[play](https://go.dev/play/p/vx8mP0U8DFk)]
### 3. Concurrency package contain some functions to support concurrent programming. eg, goroutine, channel, async.
```go
import "github.com/duke-git/lancet/v2/concurrency"
@@ -157,7 +184,7 @@ import "github.com/duke-git/lancet/v2/concurrency"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#Tee)]
[[play](https://go.dev/play/p/3TQPKnCirrP)]
### 3. Condition package contains some functions for conditional judgment. eg. And, Or, TernaryOperator...
### 4. Condition package contains some functions for conditional judgment. eg. And, Or, TernaryOperator...
```go
import "github.com/duke-git/lancet/v2/condition"
@@ -173,13 +200,13 @@ import "github.com/duke-git/lancet/v2/condition"
[[play](https://go.dev/play/p/W1SSUmt6pvr)]
- **<big>Or</big>** : returns false if neither a nor b is truthy.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/condition.md#Or)]
[[play](https://go.dev/play/p/UlQTxHaeEkq)]]
[[play](https://go.dev/play/p/UlQTxHaeEkq)]
- **<big>Xor</big>** : returns true if a or b but not both is truthy.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/condition.md#Xor)]
[[play](https://go.dev/play/p/gObZrW7ZbG8)]
- **<big>Nor</big>** : returns true if neither a nor b is truthy.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/condition.md#Nor)]
[[play](https://go.dev/play/p/g2j08F_zZky)
[[play](https://go.dev/play/p/g2j08F_zZky)]
- **<big>Xnor</big>** : returns true if both a and b or neither a nor b are truthy.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/condition.md#Xnor)]
[[play](https://go.dev/play/p/OuDB9g51643)]
@@ -190,7 +217,7 @@ import "github.com/duke-git/lancet/v2/condition"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/condition.md#TernaryOperator)]
[[play](https://go.dev/play/p/ElllPZY0guT)]
### 4. Convertor package contains some functions for data convertion.
### 5. Convertor package contains some functions for data convertion.
```go
import "github.com/duke-git/lancet/v2/convertor"
@@ -251,9 +278,11 @@ import "github.com/duke-git/lancet/v2/convertor"
[[play](https://go.dev/play/p/j4DP5dquxnk)]
- **<big>CopyProperties</big>** : copies each field from the source struct into the destination struct.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/convertor.md#CopyProperties)]
[[play](https://go.dev/play/p/oZujoB5Sgg5)]
- **<big>ToInterface</big>** : converts reflect value to its interface type.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/convertor.md#ToInterface)]
### 5. Cryptor package is for data encryption and decryption.
### 6. Cryptor package is for data encryption and decryption.
```go
import "github.com/duke-git/lancet/v2/cryptor"
@@ -357,7 +386,7 @@ import "github.com/duke-git/lancet/v2/cryptor"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/cryptor.md#RsaDecrypt)]
[[play](https://go.dev/play/p/uef0q1fz53I)]
### 6. Datetime package supports date and time format and compare.
### 7. Datetime package supports date and time format and compare.
```go
import "github.com/duke-git/lancet/v2/datetime"
@@ -374,6 +403,8 @@ import "github.com/duke-git/lancet/v2/datetime"
- **<big>AddMinute</big>** : add or sub day to the time.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/datetime.md#AddMinute)]
[[play](https://go.dev/play/p/nT1heB1KUUK)]
- **<big>AddYear</big>** : add or sub year to the time.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/datetime.md#AddYear)]
- **<big>BeginOfMinute</big>** : return the date time at the begin of minute of specific date.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/datetime.md#BeginOfMinute)]
[[play](https://go.dev/play/p/ieOLVJ9CiFT)]
@@ -455,11 +486,10 @@ import "github.com/duke-git/lancet/v2/datetime"
- **<big>ToIso8601</big>** : return iso8601 time string.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/datetime.md#ToIso8601)]
[[play](https://go.dev/play/p/mkhOHQkdeA2)]
- **<big>IsLeapYear</big>** : check if param `year` is leap year or not.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/datetime.md#IsLeapYear)]
### 7. Datastructure package constains some common data structure. eg. list, linklist, stack, queue, set, tree, graph.
### 8. Datastructure package constains some common data structure. eg. list, linklist, stack, queue, set, tree, graph.
```go
import list "github.com/duke-git/lancet/v2/datastructure/list"
@@ -491,7 +521,7 @@ import hashmap "github.com/duke-git/lancet/v2/datastructure/hashmap"
- **<big>Hashmap</big>** : hash map structure.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/datastructure/hashmap.md)]
### 8. Fileutil package implements some basic functions for file operations.
### 9. Fileutil package implements some basic functions for file operations.
```go
import "github.com/duke-git/lancet/v2/fileutil"
@@ -544,8 +574,26 @@ import "github.com/duke-git/lancet/v2/fileutil"
- **<big>UnZip</big>** : unzip the zip file and save it to dest path.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/fileutil.md#UnZip)]
[[play](https://go.dev/play/p/g0w34kS7B8m)]
- **<big>CurrentPath</big>** : return current absolute path.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/fileutil.md#CurrentPath)]
[[play](https://go.dev/play/p/s74a9iBGcSw)]
- **<big>IsZipFile</big>** : checks if file is zip file or not.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/fileutil.md#IsZipFile)]
[[play](https://go.dev/play/p/9M0g2j_uF_e)]
- **<big>FileSize</big>** : return file size in bytes.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/fileutil.md#FileSize)]
[[play](https://go.dev/play/p/H9Z05uD-Jjc)]
- **<big>MTime</big>** : return file modified time(unix timestamp).
[[doc](https://github.com/duke-git/lancet/blob/main/docs/fileutil.md#MTime)]
[[play](https://go.dev/play/p/s_Tl7lZoAaY)]
- **<big>Sha</big>** : return file sha value.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/fileutil.md#Sha)]
[[play](https://go.dev/play/p/VfEEcO2MJYf)]
- **<big>ReadCsvFile</big>** : read file content into slice.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/fileutil.md#ReadCsvFile)]
[[play](https://go.dev/play/p/OExTkhGEd3_u)]
### 9. Formatter contains some functions for data formatting.
### 10. Formatter contains some functions for data formatting.
```go
import "github.com/duke-git/lancet/v2/formatter"
@@ -556,8 +604,26 @@ import "github.com/duke-git/lancet/v2/formatter"
- **<big>Comma</big>** : add comma to a number value by every 3 numbers from right, ahead by symbol char.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/formatter.md#Comma)]
[[play](https://go.dev/play/p/eRD5k2vzUVX)]
- **<big>Pretty</big>** : pretty print data to JSON string.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/formatter.md#Pretty)]
[[play](https://go.dev/play/p/YsciGj3FH2x)]
- **<big>PrettyToWriter</big>** : pretty encode data to writer.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/formatter.md#PrettyToWriter)]
[[play](https://go.dev/play/p/LPLZ3lDi5ma)]
- **<big>DecimalBytes</big>** : returns a human readable byte size under decimal standard (base 1000).
[[doc](https://github.com/duke-git/lancet/blob/main/docs/formatter.md#DecimalBytes)]
[[play](https://go.dev/play/p/FPXs1suwRcs)]
- **<big>BinaryBytes</big>** : returns a human-readable byte size under binary standard (base 1024).
[[doc](https://github.com/duke-git/lancet/blob/main/docs/formatter.md#BinaryBytes)]
[[play](https://go.dev/play/p/G9oHHMCAZxP)]
- **<big>ParseDecimalBytes</big>** : return the human readable bytes size string into the amount it represents(base 1000).
[[doc](https://github.com/duke-git/lancet/blob/main/docs/formatter.md#ParseDecimalBytes)]
[[play](https://go.dev/play/p/Am98ybWjvjj)]
- **<big>ParseBinaryBytes</big>** : return the human readable bytes size string into the amount it represents(base 1024).
[[doc](https://github.com/duke-git/lancet/blob/main/docs/formatter.md#ParseBinaryBytes)]
[[play](https://go.dev/play/p/69v1tTT62x8)]
### 10. Function package can control the flow of function execution and support part of functional programming
### 11. Function package can control the flow of function execution and support part of functional programming
```go
import "github.com/duke-git/lancet/v2/function"
@@ -593,8 +659,7 @@ import "github.com/duke-git/lancet/v2/function"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/function.md#Watcher)]
[[play](https://go.dev/play/p/l2yrOpCLd1I)]
### 11. Maputil package includes some functions to manipulate map.
### 12. Maputil package includes some functions to manipulate map.
```go
import "github.com/duke-git/lancet/v2/maputil"
@@ -602,6 +667,9 @@ import "github.com/duke-git/lancet/v2/maputil"
#### Function list:
- **<big>MapTo</big>** : quick map any value to struct or any base type.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#MapTo)]
[[play](https://go.dev/play/p/4K7KBEPgS5M)]
- **<big>ForEach</big>** : executes iteratee funcation for every key and value pair in map.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#ForEach)]
[[play](https://go.dev/play/p/OaThj6iNVXK)]
@@ -610,14 +678,19 @@ import "github.com/duke-git/lancet/v2/maputil"
[[play](https://go.dev/play/p/fSvF3wxuNG7)]
- **<big>FilterByKeys</big>** : iterates over map, return a new map whose keys are all given keys
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#FilterByKeys)]
[[play](https://go.dev/play/p/7ov6BJHbVqh)]
- **<big>FilterByValues</big>** : iterates over map, return a new map whose values are all given values.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#FilterByValues)]
[[play](https://go.dev/play/p/P3-9MdcXegR)]
- **<big>OmitBy</big>** : the opposite of Filter, removes all the map elements for which the predicate function returns true.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#OmitBy)]
[[play](https://go.dev/play/p/YJM4Hj5hNwm)]
- **<big>OmitByKeys</big>** : the opposite of FilterByKeys, extracts all the map elements which keys are not omitted.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#OmitByKeys)]
[[play](https://go.dev/play/p/jXGrWDBfSRp)]
- **<big>OmitByValues</big>** : the opposite of FilterByValues. remov all elements whose value are in the give slice.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#OmitByValues)]
[[play](https://go.dev/play/p/XB7Y10uw20_U)]
- **<big>Intersect</big>** : iterates over maps, return a new map of key and value pairs in all given maps.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#Intersect)]
[[play](https://go.dev/play/p/Zld0oj3sjcC)]
@@ -626,6 +699,7 @@ import "github.com/duke-git/lancet/v2/maputil"
[[play](https://go.dev/play/p/xNB5bTb97Wd)]
- **<big>KeysBy</big>** : creates a slice whose element is the result of function mapper invoked by every map's key.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#KeysBy)]
[[play](https://go.dev/play/p/hI371iB8Up8)]
- **<big>Merge</big>** : merge maps, next key will overwrite previous key.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#Merge)]
[[play](https://go.dev/play/p/H95LENF1uB-)]
@@ -637,21 +711,27 @@ import "github.com/duke-git/lancet/v2/maputil"
[[play](https://go.dev/play/p/CBKdUc5FTW6)]
- **<big>ValuesBy</big>** : creates a slice whose element is the result of function mapper invoked by every map's value.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#ValuesBy)]
[[play](https://go.dev/play/p/sg9-oRidh8f)]
- **<big>MapKeys</big>** : transforms a map to other type map by manipulating it's keys.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#MapKeys)]
[[play](https://go.dev/play/p/8scDxWeBDKd)]
- **<big>MapValues</big>** : transforms a map to other type map by manipulating it's values.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#MapValues)]
[[play](https://go.dev/play/p/g92aY3fc7Iw)]
- **<big>Entries</big>** : transforms a map into array of key/value pairs.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#Entries)]
[[play](https://go.dev/play/p/Ltb11LNcElY)]
- **<big>FromEntries</big>** : creates a map based on a slice of key/value pairs.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#FromEntries)]
[[play](https://go.dev/play/p/fTdu4sCNjQO)]
- **<big>Transform</big>** : transform a map to another type map.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#Transform)]
[[play](https://go.dev/play/p/P6ovfToM3zj)]
- **<big>IsDisjoint</big>** : check two map are disjoint if they have no keys in common.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#IsDisjoint)]
[[play](https://go.dev/play/p/N9qgYg_Ho6f)]
### 12. Mathutil package implements some functions for math calculation.
### 13. Mathutil package implements some functions for math calculation.
```go
import "github.com/duke-git/lancet/v2/mathutil"
@@ -695,8 +775,30 @@ import "github.com/duke-git/lancet/v2/mathutil"
- **<big>TruncRound</big>** : round off n decimal places for int64.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#TruncRound)]
[[play](https://go.dev/play/p/aumarSHIGzP)]
- **<big>Range</big>** : Creates a slice of numbers from start with specified count, element step is 1.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#Range)]
[[play](https://go.dev/play/p/9ke2opxa8ZP)]
- **<big>RangeWithStep</big>** : Creates a slice of numbers from start to end with specified step.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#Range)]
[[play](https://go.dev/play/p/akLWz0EqOSM)]
- **<big>AngleToRadian</big>** : converts angle value to radian value.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#AngleToRadian)]
[[play](https://go.dev/play/p/CIvlICqrHql)]
- **<big>RadianToAngle</big>** : converts radian value to angle value.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#RadianToAngle)]
[[play](https://go.dev/play/p/dQtmOTUOMgi)]
- **<big>PointDistance</big>** : get two points distance.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#PointDistance)]
[[play](https://go.dev/play/p/RrG4JIaziM8)]
- **<big>IsPrime</big>** : checks if number is prime number.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#IsPrime)]
[[play](https://go.dev/play/p/Rdd8UTHZJ7u)]
- **<big>GCD</big>** : return greatest common divisor (GCD) of integers.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#GCD)]
- **<big>LCM</big>** : return Least Common Multiple (LCM) of integers.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#LCM)]
### 13. Netutil package contains functions to get net information and send http request.
### 14. Netutil package contains functions to get net information and send http request.
```go
import "github.com/duke-git/lancet/v2/netutil"
@@ -746,22 +848,30 @@ import "github.com/duke-git/lancet/v2/netutil"
- **<big>StructToUrlValues</big>** : convert struct to url valuse.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#StructToUrlValues)]
[[play](https://go.dev/play/p/pFqMkM40w9z)]
- **<big>HttpGet<sup>deprecated</sup></big>** : send get http request.
- **<big>HttpGet<sup>deprecated</sup></big>** : send http get request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpGet)]
- **<big>HttpDelete<sup>deprecated</sup></big>** : send delete http request.
- **<big>HttpDelete<sup>deprecated</sup></big>** : send http delete request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpDelete)]
- **<big>HttpPost<sup>deprecated</sup></big>** : send post http request.
- **<big>HttpPost<sup>deprecated</sup></big>** : send http post request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPost)]
- **<big>HttpPut<sup>deprecated</sup></big>** : send put http request.
- **<big>HttpPut<sup>deprecated</sup></big>** : send http put request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPut)]
- **<big>HttpPatch<sup>deprecated</sup></big>** : send patch http request.
- **<big>HttpPatch<sup>deprecated</sup></big>** : send http patch request.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#HttpPatch)]
- **<big>ParseHttpResponse</big>** : decode http response into target object.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#ParseHttpResponse)]
- **<big>DownloadFile</big>** : download the file exist in url to a local file.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#DownloadFile)]
- **<big>UploadFile</big>** : upload the file to a server.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#UploadFile)]
- **<big>IsPingConnected</big>** : checks if can ping the specified host or not.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#IsPingConnected)]
[[play](https://go.dev/play/p/q8OzTijsA87)]
- **<big>IsTelnetConnected</big>** : checks if can if can telnet the specified host or not.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/netutil.md#IsTelnetConnected)]
[[play](https://go.dev/play/p/yiLCGtQv_ZG)]
### 14. Random package implements some basic functions to generate random int and string.
### 15. Random package implements some basic functions to generate random int and string.
```go
import "github.com/duke-git/lancet/v2/random"
@@ -794,7 +904,7 @@ import "github.com/duke-git/lancet/v2/random"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/random.md#UUIdV4)]
[[play](https://go.dev/play/p/_Z9SFmr28ft)]
### 15. Retry package is for executing a function repeatedly until it was successful or canceled by the context.
### 16. Retry package is for executing a function repeatedly until it was successful or canceled by the context.
```go
import "github.com/duke-git/lancet/v2/retry"
@@ -818,7 +928,7 @@ import "github.com/duke-git/lancet/v2/retry"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/retry.md#RetryTimes)]
[[play](https://go.dev/play/p/ssfVeU2SwLO)]
### 16. Slice contains some functions to manipulate slice.
### 17. Slice contains some functions to manipulate slice.
```go
import "github.com/duke-git/lancet/v2/slice"
@@ -834,6 +944,7 @@ import "github.com/duke-git/lancet/v2/slice"
[[play](https://go.dev/play/p/_454yEHcNjf)]
- **<big>ContainBy</big>** : returns true if predicate function return true.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#ContainBy)]
[[play](https://go.dev/play/p/49tkHfX4GNc)]
- **<big>ContainSubSlice</big>** : check if the slice contain a given subslice or not.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#ContainSubSlice)]
[[play](https://go.dev/play/p/bcuQ3UT6Sev)]
@@ -890,12 +1001,19 @@ import "github.com/duke-git/lancet/v2/slice"
[[play](https://go.dev/play/p/SdPna-7qK4T)]
- **<big>FilterMap</big>** : returns a slice which apply both filtering and mapping to the given slice.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#FilterMap)]
- **<big>Find</big>** : iterates over elements of slice, returning the first one that passes a truth test on predicate function.
[[play](https://go.dev/play/p/J94SZ_9MiIe)]
- **<big>Find<sup>deprecated</sup></big>** : iterates over elements of slice, returning the first one that passes a truth test on predicate function.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Find)]
[[play](https://go.dev/play/p/CBKeBoHVLgq)]
- **<big>FindLast</big>** : return the last item that passes a truth test on predicate function.
- **<big>FindBy</big>** : iterates over elements of slice, returning the first one that passes a truth test on predicate function.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#FindBy)]
[[play](https://go.dev/play/p/n1lysBYl-GB)]
- **<big>FindLast<sup>deprecated</sup></big>** : return the last item that passes a truth test on predicate function.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#FindLast)]
[[play](https://go.dev/play/p/FFDPV_j7URd)]
- **<big>FindLastBy</big>** : iterates over elements of slice, returning the last one that passes a truth test on predicate function.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#FindLastBy)]
[[play](https://go.dev/play/p/8iqomzyCl_s)]
- **<big>Flatten</big>** : flattens slice one level.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Flatten)]
[[play](https://go.dev/play/p/hYa3cBEevtm)]
@@ -904,9 +1022,13 @@ import "github.com/duke-git/lancet/v2/slice"
[[play](https://go.dev/play/p/yjYNHPyCFaF)]
- **<big>FlatMap</big>** : manipulates a slice and transforms and flattens it to a slice of another type.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#FlatMap)]
[[play](https://go.dev/play/p/_QARWlWs1N_F)]
- **<big>ForEach</big>** : iterates over elements of slice and invokes function for each element.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#ForEach)]
[[play](https://go.dev/play/p/DrPaa4YsHRF)]
- **<big>ForEachWithBreak</big>** : iterates over elements of slice and invokes function for each element, when iteratee return false, will break the for each loop.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#ForEachWithBreak)]
[[play](https://go.dev/play/p/qScs39f3D9W)]
- **<big>GroupBy</big>** : iterate over elements of the slice, each element will be group by criteria, returns two slices.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#GroupBy)]
[[play](https://go.dev/play/p/QVkPxzPR0iA)]
@@ -940,9 +1062,15 @@ import "github.com/duke-git/lancet/v2/slice"
- **<big>Reverse</big>** : return slice of element order is reversed to the given slice.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Reverse)]
[[play](https://go.dev/play/p/8uI8f1lwNrQ)]
- **<big>Reduce</big>** : creates an slice of values by running each element of slice thru iteratee function.
- **<big>Reduce<sup>deprecated</sup></big>** : creates an slice of values by running each element of slice thru iteratee function.(Deprecated: use ReduceBy)
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Reduce)]
[[play](https://go.dev/play/p/_RfXJJWIsIm)]
- **<big>ReduceBy</big>** : produces a value from slice by accumulating the result of each element as passed through the reducer function.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#ReduceBy)]
[[play](https://go.dev/play/p/YKDpLi7gtee)]
- **<big>ReduceRight</big>** : ReduceRight is like ReduceBy, but it iterates over elements of slice from right to left.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#ReduceRight)]
[[play](https://go.dev/play/p/qT9dZC03A1K)]
- **<big>Replace</big>** : returns a copy of the slice with the first n non-overlapping instances of old replaced by new.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#Replace)]
[[play](https://go.dev/play/p/P5mZp7IhOFo)]
@@ -1013,7 +1141,126 @@ import "github.com/duke-git/lancet/v2/slice"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/slice.md#KeyBy)]
[[play](https://go.dev/play/p/uXod2LWD1Kg)]
### 17. Strutil package contains some functions to manipulate string.
### 18. Stream package implements a sequence of elements supporting sequential and operations. this package is an experiment to explore if stream in go can work as the way java does. its function is very limited.
```go
import "github.com/duke-git/lancet/v2/stream"
```
#### Function list:
- **<big>Of</big>** : creates a stream whose elements are the specified values.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Of)]
[[play](https://go.dev/play/p/jI6_iZZuVFE)]
- **<big>FromSlice</big>** : creates a stream from slice.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#FromSlice)]
[[play](https://go.dev/play/p/wywTO0XZtI4)]
- **<big>FromChannel</big>** : creates a stream from channel.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#FromChannel)]
[[play](https://go.dev/play/p/9TZYugGMhXZ)]
- **<big>FromRange</big>** : creates a number stream from start to end. both start and end are included. [start, end]
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#FromRange)]
[[play](https://go.dev/play/p/9Ex1-zcg-B-)]
- **<big>Generate</big>** : creates a stream where each element is generated by the provided generater function.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Generate)]
[[play](https://go.dev/play/p/rkOWL1yA3j9)]
- **<big>Concat</big>** : creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Concat)]
[[play](https://go.dev/play/p/HM4OlYk_OUC)]
- **<big>Distinct</big>** : creates returns a stream that removes the duplicated items.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Distinct)]
[[play](https://go.dev/play/p/eGkOSrm64cB)]
- **<big>Filter</big>** : returns a stream consisting of the elements of this stream that match the given predicate.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Filter)]
[[play](https://go.dev/play/p/MFlSANo-buc)]
- **<big>Map</big>** : returns a stream consisting of the elements of this stream that apply the given function to elements of stream.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Map)]
[[play](https://go.dev/play/p/OtNQUImdYko)]
- **<big>Peek</big>** : returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Peek)]
[[play](https://go.dev/play/p/u1VNzHs6cb2)]
- **<big>Skip</big>** : returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Skip)]
[[play](https://go.dev/play/p/fNdHbqjahum)]
- **<big>Limit</big>** : returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Limit)]
[[play](https://go.dev/play/p/qsO4aniDcGf)]
- **<big>Reverse</big>** : returns a stream whose elements are reverse order of given stream.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Reverse)]
[[play](https://go.dev/play/p/A8_zkJnLHm4)]
- **<big>Range</big>** : returns a stream whose elements are in the range from start(included) to end(excluded) original stream.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Range)]
[[play](https://go.dev/play/p/indZY5V2f4j)]
- **<big>Sorted</big>** : returns a stream consisting of the elements of this stream, sorted according to the provided less function.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Sorted)]
[[play](https://go.dev/play/p/XXtng5uonFj)]
- **<big>ForEach</big>** : performs an action for each element of this stream.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#ForEach)]
[[play](https://go.dev/play/p/Dsm0fPqcidk)]
- **<big>Reduce</big>** : performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Reduce)]
[[play](https://go.dev/play/p/6uzZjq_DJLU)]
- **<big>FindFirst</big>** : returns the first element of this stream and true, or zero value and false if the stream is empty.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#FindFirst)]
[[play](https://go.dev/play/p/9xEf0-6C1e3)]
- **<big>FindLast</big>** : returns the last element of this stream and true, or zero value and false if the stream is empty.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#FindLast)]
- **<big>Max</big>** : returns the maximum element of this stream according to the provided less function. less fuction: a > b
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Max)]
[[play](https://go.dev/play/p/fm-1KOPtGzn)]
- **<big>Min</big>** : returns the minimum element of this stream according to the provided less function. less fuction: a < b
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Min)]
[[play](https://go.dev/play/p/vZfIDgGNRe_0)]
- **<big>AllMatch</big>** : returns whether all elements of this stream match the provided predicate.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#AllMatch)]
[[play](https://go.dev/play/p/V5TBpVRs-Cx)]
- **<big>AnyMatch</big>** : returns whether any elements of this stream match the provided predicate.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#AnyMatch)]
[[play](https://go.dev/play/p/PTCnWn4OxSn)]
- **<big>NoneMatch</big>** : returns whether no elements of this stream match the provided predicate.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#NoneMatch)]
[[play](https://go.dev/play/p/iWS64pL1oo3)]
- **<big>Count</big>** : returns the count of elements in the stream.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#Count)]
[[play](https://go.dev/play/p/r3koY6y_Xo-)]
- **<big>ToSlice</big>** : returns the elements in the stream.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/stream.md#ToSlice)]
[[play](https://go.dev/play/p/jI6_iZZuVFE)]
### 19. Structs package provides several high level functions to manipulate struct, tag, and field.
```go
import "github.com/duke-git/lancet/v2/structs"
```
#### Function list:
- **<big>New</big>** : creates a `Struct` instance.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/struct.md#New)]
- **<big>ToMap</big>** : converts a valid struct to a map.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/struct.md#ToMap)]
- **<big>Fields</big>** : get all fields of a given struct, that the fields are abstract struct field.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/struct.md#Fields)]
- **<big>IsStruct</big>** : check if the struct is valid.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/struct.md#IsStruct)]
- **<big>Tag</big>** : get a `Tag` of the `Field`, `Tag` is a abstract struct field tag
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/field.md#Tag)]
- **<big>Name</big>** : get the field name.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/field.md#Name)]
- **<big>Value</big>** : get the `Field` underlying value.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/field.md#Value)]
- **<big>Kind</big>** : get the field's kind
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/field.md#Kind)]
- **<big>IsEmbedded</big>** : check if the field is an embedded field.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/field.md#IsEmbedded)]
- **<big>IsExported</big>** : check if the field is exporte
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/field.md#IsExported)]
- **<big>IsZero</big>** : check if the field is zero value
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/field.md#IsZero)]
- **<big>IsSlice</big>** : check if the field is a slice
[[doc](https://github.com/duke-git/lancet/blob/main/docs/structs/field.md#IsSlice)]
### 20. Strutil package contains some functions to manipulate string.
```go
import "github.com/duke-git/lancet/v2/strutil"
@@ -1055,6 +1302,7 @@ import "github.com/duke-git/lancet/v2/strutil"
[[play](https://go.dev/play/p/sBbBxRbs8MM)]
- **<big>Pad</big>** : pads string on the left and right side if it's shorter than size.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#Pad)]
[[play](https://go.dev/play/p/NzImQq-VF8q)]
- **<big>PadEnd</big>** : pads string with given characters on the right side if it's shorter than limit size. Padding characters are truncated if they exceed size.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#PadEnd)]
[[play](https://go.dev/play/p/9xP8rN0vz--)]
@@ -1084,10 +1332,39 @@ import "github.com/duke-git/lancet/v2/strutil"
[[play](https://go.dev/play/p/Ec2q4BzCpG-)]
- **<big>SplitWords</big>** : splits a string into words, word only contains alphabetic characters.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#SplitWords)]
[[play](https://go.dev/play/p/KLiX4WiysMM)]
- **<big>WordCount</big>** : return the number of meaningful word of a string, word only contains alphabetic characters.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#WordCount)]
[[play](https://go.dev/play/p/bj7_odx3vRf)]
- **<big>RemoveNonPrintable</big>** : remove non-printable characters from a string.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#RemoveNonPrintable)]
[[play](https://go.dev/play/p/og47F5x_jTZ)]
- **<big>StringToBytes</big>** : converts a string to byte slice without a memory allocation.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#StringToBytes)]
[[play](https://go.dev/play/p/7OyFBrf9AxA)]
- **<big>BytesToString</big>** : converts a byte slice to string without a memory allocation.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#BytesToString)]
[[play](https://go.dev/play/p/6c68HRvJecH)]
- **<big>IsBlank</big>** : checks if a string is whitespace or empty.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#IsBlank)]
[[play](https://go.dev/play/p/6zXRH_c0Qd3)]
- **<big>HasPrefixAny</big>** : checks if a string starts with any of an array of specified strings.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#HasPrefixAny)]
[[play](https://go.dev/play/p/8UUTl2C5slo)]
- **<big>HasSuffixAny</big>** : checks if a string ends with any of an array of specified strings.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#HasSuffixAny)]
[[play](https://go.dev/play/p/sKWpCQdOVkx)]
- **<big>IndexOffset</big>** : returns the index of the first instance of substr in string after offsetting the string by `idxFrom`.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#IndexOffset)]
[[play](https://go.dev/play/p/qZo4lV2fomB)]
- **<big>ReplaceWithMap</big>** : returns a copy of `str`, which is replaced by a map in unordered way, case-sensitively.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#ReplaceWithMap)]
- **<big>Trim</big>** : strips whitespace (or other characters) from the beginning and end of a string.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#Trim)]
- **<big>SplitAndTrim</big>** : splits string `str` by a string `delimiter` to a slice, and calls Trim to every element of slice.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#SplitAndTrim)]
### 19. System package contain some functions about os, runtime, shell command.
### 21. System package contain some functions about os, runtime, shell command.
```go
import "github.com/duke-git/lancet/v2/system"
@@ -1123,7 +1400,7 @@ import "github.com/duke-git/lancet/v2/system"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/system.md#GetOsBits)]
[[play](https://go.dev/play/p/ml-_XH3gJbW)]
### 19. Validator package contains some functions for data validation.
### 22. Validator package contains some functions for data validation.
```go
import "github.com/duke-git/lancet/v2/validator"
@@ -1176,18 +1453,27 @@ import "github.com/duke-git/lancet/v2/validator"
- **<big>IsEmptyString</big>** : check if the string is empty.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsEmptyString)]
[[play](https://go.dev/play/p/dpzgUjFnBCX)]
- **<big>IsFloat</big>** : check if the value is float(float32, float34) or not.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsFloat)]
[[play](https://go.dev/play/p/vsyG-sxr99_Z)]
- **<big>IsFloatStr</big>** : check if the string can convert to a float.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#LOYwS_Oyl7U)]
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsFloatStr)]
[[play](https://go.dev/play/p/LOYwS_Oyl7U)]
- **<big>IsNumber</big>** : check if the value is number(integer, float) or not.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsNumber)]
[[play](https://go.dev/play/p/mdJHOAvtsvF)]
- **<big>IsNumberStr</big>** : check if the string can convert to a number.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsNumberStr)]
[[play](https://go.dev/play/p/LzaKocSV79u)]
- **<big>IsJSON</big>** : check if the string is valid JSON.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsJSON)]
[[play](https://go.dev/play/p/sRS6c4K8jGk)]
[[play](https://go.dev/play/p/8Kip1Itjiil)]
- **<big>IsRegexMatch</big>** : check if the string match the regexp.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsRegexMatch)]
[[play](https://go.dev/play/p/z_XeZo_litG)]
- **<big>IsInt</big>** : check if the string can convert to a number.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsInt)]
[[play](https://go.dev/play/p/eFoIHbgzl-z)]
- **<big>IsIntStr</big>** : check if the string can convert to a integer.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsIntStr)]
[[play](https://go.dev/play/p/jQRtFv-a0Rk)]
@@ -1215,14 +1501,21 @@ import "github.com/duke-git/lancet/v2/validator"
- **<big>IsGBK</big>** : check if data encoding is gbk.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsGBK)]
[[play](https://go.dev/play/p/E2nt3unlmzP)]
- **<big>IsASCII</big>** : checks if string is all ASCII char.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsASCII)]
[[play](https://go.dev/play/p/hfQNPLX0jNa)]
- **<big>IsPrintable</big>** : checks if string is all printable chars.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/validator.md#IsPrintable)]
[[play](https://go.dev/play/p/Pe1FE2gdtTP)]
### 20. xerror package implements helpers for errors.
### 23. xerror package implements helpers for errors.
```go
import "github.com/duke-git/lancet/v2/xerror"
```
#### Function list:
- **<big>New</big>** : creates a new XError pointer instance with message.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/xerror.md#New)]
[[play](https://go.dev/play/p/w4oWZts7q7f)]
@@ -1247,7 +1540,7 @@ import "github.com/duke-git/lancet/v2/xerror"
- **<big>XError_Is</big>** : checks if target error is XError and Error.id of two errors are matched.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/xerror.md#XError_Is)]
[[play](https://go.dev/play/p/X6HBlsy58U9)]
- **<big>XError_Values</big>** : returns map of key and value that is set by XError.With function.
- **<big>XError_Values</big>** : returns map of key and value that is set by XError.With function.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/xerror.md#XError_Values)]
[[play](https://go.dev/play/p/ow8UISXX_Dp)]
- **<big>XError_StackTrace</big>** : returns stack trace which is compatible with pkg/errors.
@@ -1263,7 +1556,6 @@ import "github.com/duke-git/lancet/v2/xerror"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/xerror.md#TryUnwrap)]
[[play](https://go.dev/play/p/acyZVkNZEeW)]
## How to Contribute
I really appreciate any code commits which make lancet lib powerful. Please follow the rules below to create your pull request.

File diff suppressed because it is too large Load Diff

View File

@@ -200,7 +200,6 @@ func TestCountSort(t *testing.T) {
}
comparator := &peopleAgeComparator{}
sortedPeopleByAge := CountSort(peoples, comparator)
t.Log(sortedPeopleByAge)
expected := "[{d 8} {b 10} {c 17} {a 20} {e 28}]"
actual := fmt.Sprintf("%v", sortedPeopleByAge)

64
compare/compare.go Normal file
View File

@@ -0,0 +1,64 @@
// Copyright 2023 dudaodong@gmail.com. All rights resulterved.
// Use of this source code is governed by MIT license
// Package compare provides a lightweight comparison function on any type.
// reference: https://github.com/stretchr/testify
package compare
import (
"reflect"
"time"
"github.com/duke-git/lancet/v2/convertor"
)
// operator type
const (
equal = "eq"
lessThan = "lt"
greaterThan = "gt"
lessOrEqual = "le"
greaterOrEqual = "ge"
)
var (
timeType = reflect.TypeOf(time.Time{})
bytesType = reflect.TypeOf([]byte{})
)
// Equal checks if two values are equal or not. (check both type and value)
// Play: https://go.dev/play/p/wmVxR-to4lz
func Equal(left, right any) bool {
return compareValue(equal, left, right)
}
// EqualValue checks if two values are equal or not. (check value only)
// Play: https://go.dev/play/p/fxnna_LLD9u
func EqualValue(left, right any) bool {
ls, rs := convertor.ToString(left), convertor.ToString(right)
return ls == rs
}
// LessThan checks if value `left` less than value `right`.
// Play: https://go.dev/play/p/cYh7FQQj0ne
func LessThan(left, right any) bool {
return compareValue(lessThan, left, right)
}
// GreaterThan checks if value `left` greater than value `right`.
// Play: https://go.dev/play/p/9-NYDFZmIMp
func GreaterThan(left, right any) bool {
return compareValue(greaterThan, left, right)
}
// LessOrEqual checks if value `left` less than or equal to value `right`.
// Play: https://go.dev/play/p/e4T_scwoQzp
func LessOrEqual(left, right any) bool {
return compareValue(lessOrEqual, left, right)
}
// GreaterOrEqual checks if value `left` greater than or equal to value `right`.
// Play: https://go.dev/play/p/vx8mP0U8DFk
func GreaterOrEqual(left, right any) bool {
return compareValue(greaterOrEqual, left, right)
}

View File

@@ -0,0 +1,170 @@
package compare
import (
"fmt"
"time"
)
func ExampleEqual() {
result1 := Equal(1, 1)
result2 := Equal("1", "1")
result3 := Equal([]int{1, 2, 3}, []int{1, 2, 3})
result4 := Equal(map[int]string{1: "a", 2: "b"}, map[int]string{1: "a", 2: "b"})
result5 := Equal(1, "1")
result6 := Equal(1, int64(1))
result7 := Equal([]int{1, 2}, []int{1, 2, 3})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
// Output:
// true
// true
// true
// true
// false
// false
// false
}
func ExampleEqualValue() {
result1 := EqualValue(1, 1)
result2 := EqualValue(int(1), int64(1))
result3 := EqualValue(1, "1")
result4 := EqualValue(1, "2")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// true
// true
// false
}
func ExampleLessThan() {
result1 := LessThan(1, 2)
result2 := LessThan(1.1, 2.2)
result3 := LessThan("a", "b")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := LessThan(time1, time2)
result5 := LessThan(2, 1)
result6 := LessThan(1, int64(2))
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
// Output:
// true
// true
// true
// true
// false
// false
}
func ExampleGreaterThan() {
result1 := GreaterThan(2, 1)
result2 := GreaterThan(2.2, 1.1)
result3 := GreaterThan("b", "a")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := GreaterThan(time2, time1)
result5 := GreaterThan(1, 2)
result6 := GreaterThan(int64(2), 1)
result7 := GreaterThan("b", "c")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
// Output:
// true
// true
// true
// true
// false
// false
// false
}
func ExampleLessOrEqual() {
result1 := LessOrEqual(1, 1)
result2 := LessOrEqual(1.1, 2.2)
result3 := LessOrEqual("a", "b")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := LessOrEqual(time1, time2)
result5 := LessOrEqual(2, 1)
result6 := LessOrEqual(1, int64(2))
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
// Output:
// true
// true
// true
// true
// false
// false
}
func ExampleGreaterOrEqual() {
result1 := GreaterOrEqual(1, 1)
result2 := GreaterOrEqual(2.2, 1.1)
result3 := GreaterOrEqual("b", "b")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := GreaterOrEqual(time2, time1)
result5 := GreaterOrEqual(1, 2)
result6 := GreaterOrEqual(int64(2), 1)
result7 := GreaterOrEqual("b", "c")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
// Output:
// true
// true
// true
// true
// false
// false
// false
}

323
compare/compare_internal.go Normal file
View File

@@ -0,0 +1,323 @@
package compare
import (
"bytes"
"encoding/json"
"reflect"
"time"
"github.com/duke-git/lancet/v2/convertor"
)
func compareValue(operator string, left, right any) bool {
leftType, rightType := reflect.TypeOf(left), reflect.TypeOf(right)
if leftType.Kind() != rightType.Kind() {
return false
}
switch leftType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64, reflect.Bool, reflect.String:
return compareBasicValue(operator, left, right)
case reflect.Struct, reflect.Slice, reflect.Map:
return compareRefValue(operator, left, right, leftType.Kind())
}
return false
}
func compareRefValue(operator string, leftObj, rightObj any, kind reflect.Kind) bool {
leftVal, rightVal := reflect.ValueOf(leftObj), reflect.ValueOf(rightObj)
switch kind {
case reflect.Struct:
// compare time
if leftVal.CanConvert(timeType) {
timeObj1, ok := leftObj.(time.Time)
if !ok {
timeObj1 = leftVal.Convert(timeType).Interface().(time.Time)
}
timeObj2, ok := rightObj.(time.Time)
if !ok {
timeObj2 = rightVal.Convert(timeType).Interface().(time.Time)
}
return compareBasicValue(operator, timeObj1.UnixNano(), timeObj2.UnixNano())
}
// for other struct type, only process equal operator
switch operator {
case equal:
return objectsAreEqualValues(leftObj, rightObj)
}
case reflect.Slice:
// compare []byte
if leftVal.CanConvert(bytesType) {
bytesObj1, ok := leftObj.([]byte)
if !ok {
bytesObj1 = leftVal.Convert(bytesType).Interface().([]byte)
}
bytesObj2, ok := rightObj.([]byte)
if !ok {
bytesObj2 = rightVal.Convert(bytesType).Interface().([]byte)
}
switch operator {
case equal:
if bytes.Compare(bytesObj1, bytesObj2) == 0 {
return true
}
case lessThan:
if bytes.Compare(bytesObj1, bytesObj2) == -1 {
return true
}
case greaterThan:
if bytes.Compare(bytesObj1, bytesObj2) == 1 {
return true
}
case lessOrEqual:
if bytes.Compare(bytesObj1, bytesObj2) <= 0 {
return true
}
case greaterOrEqual:
if bytes.Compare(bytesObj1, bytesObj2) >= 0 {
return true
}
}
}
// for other type slice, only process equal operator
switch operator {
case equal:
return reflect.DeepEqual(leftObj, rightObj)
}
case reflect.Map:
// only process equal operator
switch operator {
case equal:
return reflect.DeepEqual(leftObj, rightObj)
}
}
return false
}
func objectsAreEqualValues(expected, actual interface{}) bool {
if objectsAreEqual(expected, actual) {
return true
}
actualType := reflect.TypeOf(actual)
if actualType == nil {
return false
}
expectedValue := reflect.ValueOf(expected)
if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
// Attempt comparison after type conversion
return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
}
return false
}
func objectsAreEqual(expected, actual interface{}) bool {
if expected == nil || actual == nil {
return expected == actual
}
exp, ok := expected.([]byte)
if !ok {
return reflect.DeepEqual(expected, actual)
}
act, ok := actual.([]byte)
if !ok {
return false
}
if exp == nil || act == nil {
return exp == nil && act == nil
}
return bytes.Equal(exp, act)
}
// compareBasic compare basic value: integer, float, string, bool
func compareBasicValue(operator string, leftValue, rightValue any) bool {
if leftValue == nil && rightValue == nil && operator == equal {
return true
}
switch leftVal := leftValue.(type) {
case json.Number:
if left, err := leftVal.Float64(); err == nil {
switch rightVal := rightValue.(type) {
case json.Number:
if right, err := rightVal.Float64(); err == nil {
switch operator {
case equal:
if left == right {
return true
}
case lessThan:
if left < right {
return true
}
case greaterThan:
if left > right {
return true
}
case lessOrEqual:
if left <= right {
return true
}
case greaterOrEqual:
if left >= right {
return true
}
}
}
case float32, float64, int, uint, int8, uint8, int16, uint16, int32, uint32, int64, uint64:
right, err := convertor.ToFloat(rightValue)
if err != nil {
return false
}
switch operator {
case equal:
if left == right {
return true
}
case lessThan:
if left < right {
return true
}
case greaterThan:
if left > right {
return true
}
case lessOrEqual:
if left <= right {
return true
}
case greaterOrEqual:
if left >= right {
return true
}
}
}
}
case float32, float64, int, uint, int8, uint8, int16, uint16, int32, uint32, int64, uint64:
left, err := convertor.ToFloat(leftValue)
if err != nil {
return false
}
switch rightVal := rightValue.(type) {
case json.Number:
if right, err := rightVal.Float64(); err == nil {
switch operator {
case equal:
if left == right {
return true
}
case lessThan:
if left < right {
return true
}
case greaterThan:
if left > right {
return true
}
case lessOrEqual:
if left <= right {
return true
}
case greaterOrEqual:
if left >= right {
return true
}
}
}
case float32, float64, int, uint, int8, uint8, int16, uint16, int32, uint32, int64, uint64:
right, err := convertor.ToFloat(rightValue)
if err != nil {
return false
}
switch operator {
case equal:
if left == right {
return true
}
case lessThan:
if left < right {
return true
}
case greaterThan:
if left > right {
return true
}
case lessOrEqual:
if left <= right {
return true
}
case greaterOrEqual:
if left >= right {
return true
}
}
}
case string:
left := leftVal
switch right := rightValue.(type) {
case string:
switch operator {
case equal:
if left == right {
return true
}
case lessThan:
if left < right {
return true
}
case greaterThan:
if left > right {
return true
}
case lessOrEqual:
if left <= right {
return true
}
case greaterOrEqual:
if left >= right {
return true
}
}
}
case bool:
left := leftVal
switch right := rightValue.(type) {
case bool:
switch operator {
case equal:
if left == right {
return true
}
}
}
}
return false
}

134
compare/compare_test.go Normal file
View File

@@ -0,0 +1,134 @@
package compare
import (
"testing"
"time"
"github.com/duke-git/lancet/v2/internal"
)
func TestEqual(t *testing.T) {
assert := internal.NewAssert(t, "TestEqual")
assert.Equal(true, Equal(1, 1))
assert.Equal(true, Equal(int64(1), int64(1)))
assert.Equal(true, Equal("a", "a"))
assert.Equal(true, Equal(true, true))
assert.Equal(true, Equal([]int{1, 2, 3}, []int{1, 2, 3}))
assert.Equal(true, Equal(map[int]string{1: "a", 2: "b"}, map[int]string{1: "a", 2: "b"}))
assert.Equal(false, Equal(1, 2))
assert.Equal(false, Equal(1, int64(1)))
assert.Equal(false, Equal("a", "b"))
assert.Equal(false, Equal(true, false))
assert.Equal(false, Equal([]int{1, 2}, []int{1, 2, 3}))
assert.Equal(false, Equal(map[int]string{1: "a", 2: "b"}, map[int]string{1: "a"}))
time1 := time.Now()
time2 := time1.Add(time.Second)
time3 := time1.Add(time.Second)
assert.Equal(false, Equal(time1, time2))
assert.Equal(true, Equal(time2, time3))
st1 := struct {
A string
B string
}{
A: "a",
B: "b",
}
st2 := struct {
A string
B string
}{
A: "a",
B: "b",
}
st3 := struct {
A string
B string
}{
A: "a1",
B: "b",
}
assert.Equal(true, Equal(st1, st2))
assert.Equal(false, Equal(st1, st3))
}
func TestEqualValue(t *testing.T) {
assert := internal.NewAssert(t, "TestEqualValue")
assert.Equal(true, EqualValue(1, 1))
assert.Equal(true, EqualValue(int(1), int64(1)))
assert.Equal(true, EqualValue(1, "1"))
assert.Equal(false, EqualValue(1, "2"))
}
func TestLessThan(t *testing.T) {
assert := internal.NewAssert(t, "TestLessThan")
assert.Equal(true, LessThan(1, 2))
assert.Equal(true, LessThan(1.1, 2.2))
assert.Equal(true, LessThan("a", "b"))
time1 := time.Now()
time2 := time1.Add(time.Second)
assert.Equal(true, LessThan(time1, time2))
assert.Equal(false, LessThan(1, 1))
assert.Equal(false, LessThan(1, int64(1)))
}
func TestGreaterThan(t *testing.T) {
assert := internal.NewAssert(t, "TestGreaterThan")
assert.Equal(true, GreaterThan(2, 1))
assert.Equal(true, GreaterThan(2.2, 1.1))
assert.Equal(true, GreaterThan("b", "a"))
time1 := time.Now()
time2 := time1.Add(time.Second)
assert.Equal(true, GreaterThan(time2, time1))
assert.Equal(false, GreaterThan(1, 2))
assert.Equal(false, GreaterThan(int64(2), 1))
assert.Equal(false, GreaterThan("b", "c"))
}
func TestLessOrEqual(t *testing.T) {
assert := internal.NewAssert(t, "TestLessOrEqual")
assert.Equal(true, LessOrEqual(1, 2))
assert.Equal(true, LessOrEqual(1, 1))
assert.Equal(true, LessOrEqual(1.1, 2.2))
assert.Equal(true, LessOrEqual("a", "b"))
time1 := time.Now()
time2 := time1.Add(time.Second)
assert.Equal(true, LessOrEqual(time1, time2))
assert.Equal(false, LessOrEqual(2, 1))
assert.Equal(false, LessOrEqual(1, int64(2)))
}
func TestGreaterOrEqual(t *testing.T) {
assert := internal.NewAssert(t, "TestGreaterThan")
assert.Equal(true, GreaterOrEqual(2, 1))
assert.Equal(true, GreaterOrEqual(1, 1))
assert.Equal(true, GreaterOrEqual(2.2, 1.1))
assert.Equal(true, GreaterOrEqual("b", "b"))
time1 := time.Now()
time2 := time1.Add(time.Second)
assert.Equal(true, GreaterOrEqual(time2, time1))
assert.Equal(false, GreaterOrEqual(1, 2))
assert.Equal(false, GreaterOrEqual(int64(2), 1))
assert.Equal(false, GreaterOrEqual("b", "c"))
}

View File

@@ -1,7 +1,7 @@
// Copyright 2021 dudaodong@gmail.com. All rights reserved.
// Use of this source code is governed by MIT license
// Package concurrency contain some functions to support concurrent programming. eg, goroutine, channel, async.
// Package concurrency contain some functions to support concurrent programming. eg, goroutine, channel.
package concurrency
import (

View File

@@ -181,7 +181,6 @@ func TestBridge(t *testing.T) {
index := 0
for val := range c.Bridge(ctx, genVals()) {
// t.Logf("%v ", val) //0 1 2 3 4 5 6 7 8 9
assert.Equal(index, val)
index++
}

View File

@@ -13,9 +13,10 @@ import (
"fmt"
"math"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/duke-git/lancet/v2/structs"
)
// ToBool convert string to boolean.
@@ -235,31 +236,7 @@ func ToMap[T any, K comparable, V any](array []T, iteratee func(T) (K, V)) map[K
// map key is specified same as struct field tag `json` value.
// Play: https://go.dev/play/p/KYGYJqNUBOI
func StructToMap(value any) (map[string]any, error) {
v := reflect.ValueOf(value)
t := reflect.TypeOf(value)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf("data type %T not support, shuld be struct or pointer to struct", value)
}
result := make(map[string]any)
fieldNum := t.NumField()
pattern := `^[A-Z]`
regex := regexp.MustCompile(pattern)
for i := 0; i < fieldNum; i++ {
name := t.Field(i).Name
tag := t.Field(i).Tag.Get("json")
if regex.MatchString(name) && tag != "" {
//result[name] = v.Field(i).Interface()
result[tag] = v.Field(i).Interface()
}
}
return result, nil
return structs.ToMap(value)
}
// MapToSlice convert map to slice based on iteratee function.
@@ -343,44 +320,58 @@ func DeepClone[T any](src T) T {
}
// CopyProperties copies each field from the source into the destination. It recursively copies struct pointers and interfaces that contain struct pointers.
// Play: todo
func CopyProperties[T, U any](dst T, src U) (err error) {
defer func() {
if e := recover(); e != nil {
err = errors.New(fmt.Sprintf("%v", e))
}
}()
dstType, dstValue := reflect.TypeOf(dst), reflect.ValueOf(dst)
srcType, srcValue := reflect.TypeOf(src), reflect.ValueOf(src)
// use json.Marshal/Unmarshal, so json tag should be set for fields of dst and src struct.
// Play: https://go.dev/play/p/oZujoB5Sgg5
func CopyProperties[T, U any](dst T, src U) error {
dstType, srcType := reflect.TypeOf(dst), reflect.TypeOf(src)
if dstType.Kind() != reflect.Ptr || dstType.Elem().Kind() != reflect.Struct {
return errors.New("CopyProperties: param dst should be struct pointer")
return errors.New("CopyProperties: parameter dst should be struct pointer")
}
if srcType.Kind() == reflect.Ptr {
srcType, srcValue = srcType.Elem(), srcValue.Elem()
srcType = srcType.Elem()
}
if srcType.Kind() != reflect.Struct {
return errors.New("CopyProperties: param src should be a struct or struct pointer")
return errors.New("CopyProperties: parameter src should be a struct or struct pointer")
}
dstType, dstValue = dstType.Elem(), dstValue.Elem()
propertyNums := dstType.NumField()
for i := 0; i < propertyNums; i++ {
property := dstType.Field(i)
propertyValue := srcValue.FieldByName(property.Name)
if !propertyValue.IsValid() || property.Type != propertyValue.Type() {
continue
}
if dstValue.Field(i).CanSet() {
dstValue.Field(i).Set(propertyValue)
}
bytes, err := json.Marshal(src)
if err != nil {
return fmt.Errorf("CopyProperties: unable to marshal src: %s", err)
}
err = json.Unmarshal(bytes, dst)
if err != nil {
return fmt.Errorf("CopyProperties: unable to unmarshal into dst: %s", err)
}
return nil
}
// ToInterface converts reflect value to its interface type.
// Play: todo
func ToInterface(v reflect.Value) (value interface{}, ok bool) {
if v.IsValid() && v.CanInterface() {
return v.Interface(), true
}
switch v.Kind() {
case reflect.Bool:
return v.Bool(), true
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int(), true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint(), true
case reflect.Float32, reflect.Float64:
return v.Float(), true
case reflect.Complex64, reflect.Complex128:
return v.Complex(), true
case reflect.String:
return v.String(), true
case reflect.Ptr:
return ToInterface(v.Elem())
case reflect.Interface:
return ToInterface(v.Elem())
default:
return nil, false
}
}

View File

@@ -2,6 +2,7 @@ package convertor
import (
"fmt"
"reflect"
"strconv"
)
@@ -255,12 +256,12 @@ func ExampleDecodeByte() {
func ExampleDeepClone() {
type Struct struct {
Str string
Int int
Float float64
Bool bool
Nil interface{}
unexported string
Str string
Int int
Float float64
Bool bool
Nil interface{}
// unexported string
}
cases := []interface{}{
@@ -293,47 +294,73 @@ func ExampleDeepClone() {
// 1 false
// 0.1 false
// map[a:1 b:2] false
// &{test 1 0.1 true <nil> } false
// &{test 1 0.1 true <nil>} false
}
func ExampleCopyProperties() {
type Address struct {
Country string
ZipCode string
type Disk struct {
Name string `json:"name"`
Total string `json:"total"`
Used string `json:"used"`
Percent float64 `json:"percent"`
}
type User struct {
Name string
Age int
Role string
Addr Address
Hobbys []string
salary int
type DiskVO struct {
Name string `json:"name"`
Total string `json:"total"`
Used string `json:"used"`
Percent float64 `json:"percent"`
}
type Employee struct {
Name string
Age int
Role string
Addr Address
Hobbys []string
salary int
type Indicator struct {
Id string `json:"id"`
Ip string `json:"ip"`
UpTime string `json:"upTime"`
LoadAvg string `json:"loadAvg"`
Cpu int `json:"cpu"`
Disk []Disk `json:"disk"`
Stop chan bool `json:"-"`
}
user := User{Name: "user001", Age: 10, Role: "Admin", Addr: Address{Country: "CN", ZipCode: "001"}, Hobbys: []string{"a", "b"}, salary: 1000}
type IndicatorVO struct {
Id string `json:"id"`
Ip string `json:"ip"`
UpTime string `json:"upTime"`
LoadAvg string `json:"loadAvg"`
Cpu int64 `json:"cpu"`
Disk []DiskVO `json:"disk"`
}
employee1 := Employee{}
CopyProperties(&employee1, &user)
indicator := &Indicator{Id: "001", Ip: "127.0.0.1", Cpu: 1, Disk: []Disk{
{Name: "disk-001", Total: "100", Used: "1", Percent: 10},
{Name: "disk-002", Total: "200", Used: "1", Percent: 20},
{Name: "disk-003", Total: "300", Used: "1", Percent: 30},
}}
employee2 := Employee{Name: "employee001", Age: 20, Role: "User",
Addr: Address{Country: "UK", ZipCode: "002"}, salary: 500}
indicatorVO := IndicatorVO{}
CopyProperties(&employee2, &user)
CopyProperties(&indicatorVO, indicator)
fmt.Println(employee1)
fmt.Println(employee2)
fmt.Println(indicatorVO.Id)
fmt.Println(indicatorVO.Ip)
fmt.Println(len(indicatorVO.Disk))
// Output:
// {user001 10 Admin {CN 001} [a b] 0}
// {user001 10 Admin {CN 001} [a b] 500}
// 001
// 127.0.0.1
// 3
}
func ExampleToInterface() {
val := reflect.ValueOf("abc")
iVal, ok := ToInterface(val)
fmt.Printf("%T\n", iVal)
fmt.Printf("%v\n", iVal)
fmt.Println(ok)
// Output:
// string
// abc
// true
}

View File

@@ -180,18 +180,36 @@ func TestToMap(t *testing.T) {
func TestStructToMap(t *testing.T) {
assert := internal.NewAssert(t, "TestStructToMap")
type People struct {
Name string `json:"name"`
age int
}
p := People{
"test",
100,
}
pm, _ := StructToMap(p)
t.Run("StructToMap", func(_ *testing.T) {
type People struct {
Name string `json:"name"`
age int
}
p := People{
"test",
100,
}
pm, _ := StructToMap(p)
var expected = map[string]any{"name": "test"}
assert.Equal(expected, pm)
})
expected := map[string]any{"name": "test"}
assert.Equal(expected, pm)
t.Run("StructToMapWithJsonAttr", func(_ *testing.T) {
type People struct {
Name string `json:"name,omitempty"` // json tag with attribute
Phone string `json:"phone"` // json tag without attribute
Sex string `json:"-"` // ignore
age int // no tag
}
p := People{
Phone: "1111",
Sex: "male",
age: 100,
}
pm, _ := StructToMap(p)
var expected = map[string]any{"phone": "1111"}
assert.Equal(expected, pm)
})
}
func TestMapToSlice(t *testing.T) {
@@ -259,12 +277,12 @@ func TestDeepClone(t *testing.T) {
// assert := internal.NewAssert(t, "TestDeepClone")
type Struct struct {
Str string
Int int
Float float64
Bool bool
Nil interface{}
unexported string
Str string
Int int
Float float64
Bool bool
Nil interface{}
// unexported string
}
cases := []interface{}{
@@ -288,7 +306,6 @@ func TestDeepClone(t *testing.T) {
for i, item := range cases {
cloned := DeepClone(item)
t.Log(cloned)
if &cloned == &item {
t.Fatalf("[TestDeepClone case #%d failed]: equal pointer", i)
}
@@ -302,49 +319,80 @@ func TestDeepClone(t *testing.T) {
func TestCopyProperties(t *testing.T) {
assert := internal.NewAssert(t, "TestCopyProperties")
type Address struct {
Country string
ZipCode string
type Disk struct {
Name string `json:"name"`
Total string `json:"total"`
Used string `json:"used"`
Percent float64 `json:"percent"`
}
type User struct {
Name string
Age int
Role string
Addr Address
Hobbys []string
salary int
type DiskVO struct {
Name string `json:"name"`
Total string `json:"total"`
Used string `json:"used"`
Percent float64 `json:"percent"`
}
type Employee struct {
Name string
Age int
Role string
Addr Address
Hobbys []string
salary int
type Indicator struct {
Id string `json:"id"`
Ip string `json:"ip"`
UpTime string `json:"upTime"`
LoadAvg string `json:"loadAvg"`
Cpu int `json:"cpu"`
Disk []Disk `json:"disk"`
Stop chan bool `json:"-"`
}
user := User{Name: "user001", Age: 10, Role: "Admin", Addr: Address{Country: "CN", ZipCode: "001"}, Hobbys: []string{"a", "b"}, salary: 1000}
type IndicatorVO struct {
Id string `json:"id"`
Ip string `json:"ip"`
UpTime string `json:"upTime"`
LoadAvg string `json:"loadAvg"`
Cpu int64 `json:"cpu"`
Disk []DiskVO `json:"disk"`
}
employee1 := Employee{}
indicator := &Indicator{Id: "001", Ip: "127.0.0.1", Cpu: 1, Disk: []Disk{
{Name: "disk-001", Total: "100", Used: "1", Percent: 10},
{Name: "disk-002", Total: "200", Used: "1", Percent: 20},
{Name: "disk-003", Total: "300", Used: "1", Percent: 30},
}}
err := CopyProperties(&employee1, &user)
indicatorVO := IndicatorVO{}
err := CopyProperties(&indicatorVO, indicator)
assert.IsNil(err)
assert.Equal("user001", employee1.Name)
assert.Equal("Admin", employee1.Role)
assert.Equal("CN", employee1.Addr.Country)
assert.Equal(0, employee1.salary)
employee2 := Employee{Name: "employee001", Age: 20, Role: "User",
Addr: Address{Country: "UK", ZipCode: "002"}, salary: 500}
err = CopyProperties(&employee2, &user)
assert.IsNil(err)
assert.Equal("user001", employee2.Name)
assert.Equal("Admin", employee2.Role)
assert.Equal("CN", employee2.Addr.Country)
assert.Equal(500, employee2.salary)
assert.Equal("001", indicatorVO.Id)
assert.Equal("127.0.0.1", indicatorVO.Ip)
assert.Equal(3, len(indicatorVO.Disk))
}
func TestToInterface(t *testing.T) {
assert := internal.NewAssert(t, "TestToInterface")
cases := []reflect.Value{
reflect.ValueOf("abc"),
reflect.ValueOf(int(0)), reflect.ValueOf(int8(1)), reflect.ValueOf(int16(-1)), reflect.ValueOf(int32(123)), reflect.ValueOf(int64(123)),
reflect.ValueOf(uint(123)), reflect.ValueOf(uint8(123)), reflect.ValueOf(uint16(123)), reflect.ValueOf(uint32(123)), reflect.ValueOf(uint64(123)),
reflect.ValueOf(float64(12.3)), reflect.ValueOf(float32(12.3)),
reflect.ValueOf(true), reflect.ValueOf(false),
}
expected := []interface{}{
"abc",
0, int8(1), int16(-1), int32(123), int64(123),
uint(123), uint8(123), uint16(123), uint32(123), uint64(123),
float64(12.3), float32(12.3),
true, false,
}
for i := 0; i < len(cases); i++ {
actual, _ := ToInterface(cases[i])
assert.Equal(expected[i], actual)
}
nilVal, ok := ToInterface(reflect.ValueOf(nil))
assert.EqualValues(nil, nilVal)
assert.Equal(false, ok)
}

View File

@@ -17,7 +17,7 @@ type mapNode struct {
next *mapNode
}
//HashMap implements a hash map
// HashMap implements a hash map
type HashMap struct {
capacity uint64
size uint64

View File

@@ -64,7 +64,6 @@ func TestHashMap_KeysValues(t *testing.T) {
keys := hm.Keys()
values := hm.Values()
t.Log(keys, values)
assert.Equal(3, len(values))
assert.Equal(3, len(keys))

View File

@@ -171,3 +171,25 @@ func (s Set[T]) Minus(comparedSet Set[T]) Set[T] {
return set
}
// EachWithBreak iterates over elements of a set and invokes function for each element,
// when iteratee return false, will break the for each loop.
func (s Set[T]) EachWithBreak(iteratee func(item T) bool) {
for _, v := range s.Values() {
if !iteratee(v) {
break
}
}
}
// Pop delete the top element of set then return it, if set is empty, return nil-value of T and false.
func (s Set[T]) Pop() (v T, ok bool) {
if len(s) > 0 {
items := s.Values()
item := items[len(s)-1]
delete(s, item)
return item, true
}
return v, false
}

View File

@@ -192,3 +192,40 @@ func TestSet_Minus(t *testing.T) {
assert.Equal(NewSet(1), set1.Minus(set2))
assert.Equal(NewSet(4, 5), set2.Minus(set3))
}
func TestEachWithBreak(t *testing.T) {
// s := NewSet(1, 2, 3, 4, 5)
// var sum int
// s.EachWithBreak(func(n int) bool {
// if n > 3 {
// return false
// }
// sum += n
// return true
// })
// assert := internal.NewAssert(t, "TestEachWithBreak")
// assert.Equal(6, sum)
}
// func TestPop(t *testing.T) {
// assert := internal.NewAssert(t, "TestPop")
// s := NewSet[int]()
// val, ok := s.Pop()
// assert.Equal(0, val)
// assert.Equal(false, ok)
// s.Add(1)
// s.Add(2)
// s.Add(3)
// // s = NewSet(1, 2, 3, 4, 5)
// val, ok = s.Pop()
// assert.Equal(3, val)
// assert.Equal(true, ok)
// }

View File

@@ -40,7 +40,6 @@ func TestBSTree_PreOrderTraverse(t *testing.T) {
bstree.Insert(4)
acturl := bstree.PreOrderTraverse()
t.Log(acturl)
assert.Equal([]int{6, 5, 2, 4, 7}, acturl)
}
@@ -55,7 +54,6 @@ func TestBSTree_PostOrderTraverse(t *testing.T) {
bstree.Insert(4)
acturl := bstree.PostOrderTraverse()
t.Log(acturl)
assert.Equal([]int{5, 2, 4, 7, 6}, acturl)
}
@@ -70,7 +68,6 @@ func TestBSTree_InOrderTraverse(t *testing.T) {
bstree.Insert(4)
acturl := bstree.InOrderTraverse()
t.Log(acturl)
assert.Equal([]int{2, 4, 5, 6, 7}, acturl)
}
@@ -85,7 +82,6 @@ func TestBSTree_LevelOrderTraverse(t *testing.T) {
bstree.Insert(4)
acturl := bstree.LevelOrderTraverse()
t.Log(acturl)
assert.Equal([]int{6, 5, 7, 2, 4}, acturl)
}
@@ -102,14 +98,12 @@ func TestBSTree_Delete(t *testing.T) {
bstree.Delete(4)
acturl1 := bstree.InOrderTraverse()
t.Log(acturl1)
assert.Equal([]int{2, 5, 6, 7}, acturl1)
//todo
// bstree.DeletetNode(6, comparator)
// bstree.Print()
// acturl2 := bstree.InOrderTraverse()
// t.Log(acturl2)
// assert.Equal([]int{2, 5, 7}, acturl2)
}

View File

@@ -20,9 +20,8 @@ func TestToFormat(t *testing.T) {
assert := internal.NewAssert(t, "TestToFormat")
tm, err := NewFormat("2022-03-18 17:04:05")
t.Log("TestToFormat", tm.ToFormat())
assert.IsNil(err)
t.Log("ToFormat -> ", tm.ToFormat())
}
func TestToFormatForTpl(t *testing.T) {
@@ -32,9 +31,9 @@ func TestToFormatForTpl(t *testing.T) {
assert.IsNotNil(err)
tm, err := NewFormat("2022-03-18 17:04:05")
// assert.Equal("2022/03/18 17:04:05", tm.ToFormatForTpl("2006/01/02 15:04:05"))
t.Log("TestToFormatForTpl", tm.ToFormatForTpl("2006/01/02 15:04:05"))
assert.IsNil(err)
t.Log("ToFormatForTpl -> ", tm.ToFormatForTpl("2006/01/02 15:04:05"))
}
func TestToIso8601(t *testing.T) {
@@ -44,7 +43,7 @@ func TestToIso8601(t *testing.T) {
assert.IsNotNil(err)
tm, err := NewISO8601("2006-01-02T15:04:05.999Z")
t.Log("TestToIso8601", tm.ToIso8601())
// assert.Equal("2006-01-02T23:04:05+08:00", tm.ToIso8601())
assert.IsNil(err)
t.Log("ToIso8601 -> ", tm.ToIso8601())
}

View File

@@ -72,6 +72,12 @@ func AddDay(t time.Time, day int64) time.Time {
return t.Add(24 * time.Hour * time.Duration(day))
}
// AddYear add or sub year to the time.
// Play: todo
func AddYear(t time.Time, year int64) time.Time {
return t.Add(365 * 24 * time.Hour * time.Duration(year))
}
// GetNowDate return format yyyy-mm-dd of current date.
// Play: https://go.dev/play/p/PvfkPpcpBBf
func GetNowDate() string {
@@ -218,3 +224,9 @@ func BeginOfYear(t time.Time) time.Time {
func EndOfYear(t time.Time) time.Time {
return BeginOfYear(t).AddDate(1, 0, 0).Add(-time.Nanosecond)
}
// IsLeapYear check if param year is leap year or not.
// Play: todo
func IsLeapYear(year int) bool {
return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}

View File

@@ -57,6 +57,23 @@ func ExampleAddMinute() {
// -2m0s
}
func ExampleAddYear() {
now := time.Now()
after1Year := AddYear(now, 1)
diff1 := after1Year.Sub(now)
before1Year := AddYear(now, -1)
diff2 := before1Year.Sub(now)
fmt.Println(diff1)
fmt.Println(diff2)
// Output:
// 8760h0m0s
// -8760h0m0s
}
func ExampleGetNowDate() {
result := GetNowDate()
@@ -321,3 +338,15 @@ func ExampleNewUnixNow() {
// // Output:
// // 2006-01-02T23:04:05+08:00
// }
func ExampleIsLeapYear() {
result1 := IsLeapYear(2000)
result2 := IsLeapYear(2001)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}

View File

@@ -7,6 +7,19 @@ import (
"github.com/duke-git/lancet/v2/internal"
)
func TestAddYear(t *testing.T) {
assert := internal.NewAssert(t, "TestAddDay")
now := time.Now()
after2Years := AddYear(now, 1)
diff1 := after2Years.Sub(now)
assert.Equal(float64(8760), diff1.Hours())
before2Years := AddYear(now, -1)
diff2 := before2Years.Sub(now)
assert.Equal(float64(-8760), diff2.Hours())
}
func TestAddDay(t *testing.T) {
assert := internal.NewAssert(t, "TestAddDay")
@@ -230,3 +243,13 @@ func TestEndOfYear(t *testing.T) {
assert.Equal(expected, actual)
}
func TestIsLeapYear(t *testing.T) {
assert := internal.NewAssert(t, "TestEndOfYear")
result1 := IsLeapYear(2000)
result2 := IsLeapYear(2001)
assert.Equal(true, result1)
assert.Equal(false, result2)
}

326
docs/compare.md Normal file
View File

@@ -0,0 +1,326 @@
# Compare
Package compare provides a lightweight comparison function on any type.
<div STYLE="page-break-after: always;"></div>
## Source:
- [https://github.com/duke-git/lancet/blob/main/compare/compare.go](https://github.com/duke-git/lancet/blob/main/compare/compare.go)
- [https://github.com/duke-git/lancet/blob/main/compare/compare_internal.go](https://github.com/duke-git/lancet/blob/main/compare/compare_internal.go)
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/v2/condition"
)
```
<div STYLE="page-break-after: always;"></div>
## Index
- [Equal](#Equal)
- [EqualValue](#EqualValue)
- [LessThan](#LessThan)
- [GreaterThan](#GreaterThan)
- [LessOrEqual](#LessOrEqual)
- [GreaterOrEqual](#GreaterOrEqual)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="Equal">Equal</span>
<p>Checks if two values are equal or not. (check both type and value)</p>
<b>Signature:</b>
```go
func Equal(left, right any) bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.Equal(1, 1)
result2 := compare.Equal("1", "1")
result3 := compare.Equal([]int{1, 2, 3}, []int{1, 2, 3})
result4 := compare.Equal(map[int]string{1: "a", 2: "b"}, map[int]string{1: "a", 2: "b"})
result5 := compare.Equal(1, "1")
result6 := compare.Equal(1, int64(1))
result7 := compare.Equal([]int{1, 2}, []int{1, 2, 3})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
// Output:
// true
// true
// true
// true
// false
// false
// false
}
```
### <span id="EqualValue">EqualValue</span>
<p>Checks if two values are equal or not. (check value only)</p>
<b>Signature:</b>
```go
func EqualValue(left, right any) bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.EqualValue(1, 1)
result2 := compare.EqualValue(int(1), int64(1))
result3 := compare.EqualValue(1, "1")
result4 := compare.EqualValue(1, "2")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// true
// true
// false
}
```
### <span id="LessThan">LessThan</span>
<p>Checks if value `left` less than value `right`.</p>
<b>Signature:</b>
```go
func LessThan(left, right any) bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.LessThan(1, 2)
result2 := compare.LessThan(1.1, 2.2)
result3 := compare.LessThan("a", "b")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := compare.LessThan(time1, time2)
result5 := compare.LessThan(2, 1)
result6 := compare.LessThan(1, int64(2))
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
// Output:
// true
// true
// true
// true
// false
// false
}
```
### <span id="GreaterThan">GreaterThan</span>
<p>Checks if value `left` greater than value `right`.</p>
<b>Signature:</b>
```go
func GreaterThan(left, right any) bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.GreaterThan(2, 1)
result2 := compare.GreaterThan(2.2, 1.1)
result3 := compare.GreaterThan("b", "a")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := compare.GreaterThan(time2, time1)
result5 := compare.GreaterThan(1, 2)
result6 := compare.GreaterThan(int64(2), 1)
result7 := compare.GreaterThan("b", "c")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
// Output:
// true
// true
// true
// true
// false
// false
// false
}
```
### <span id="LessOrEqual">LessOrEqual</span>
<p>Checks if value `left` less than or equal than value `right`.</p>
<b>Signature:</b>
```go
func LessOrEqual(left, right any) bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.LessOrEqual(1, 1)
result2 := compare.LessOrEqual(1.1, 2.2)
result3 := compare.LessOrEqual("a", "b")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := compare.LessOrEqual(time1, time2)
result5 := compare.LessOrEqual(2, 1)
result6 := compare.LessOrEqual(1, int64(2))
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
// Output:
// true
// true
// true
// true
// false
// false
}
```
### <span id="GreaterOrEqual">GreaterOrEqual</span>
<p>Checks if value `left` less greater or equal than value `right`.</p>
<b>Signature:</b>
```go
func GreaterOrEqual(left, right any) bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.GreaterOrEqual(1, 1)
result2 := compare.GreaterOrEqual(2.2, 1.1)
result3 := compare.GreaterOrEqual("b", "b")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := compare.GreaterOrEqual(time2, time1)
result5 := compare.GreaterOrEqual(1, 2)
result6 := compare.GreaterOrEqual(int64(2), 1)
result7 := compare.GreaterOrEqual("b", "c")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
// Output:
// true
// true
// true
// true
// false
// false
// false
}
```

326
docs/compare_zh-CN.md Normal file
View File

@@ -0,0 +1,326 @@
# Compare
compare包提供几个轻量级的类型比较函数。
<div STYLE="page-break-after: always;"></div>
## 源码:
- [https://github.com/duke-git/lancet/blob/main/compare/compare.go](https://github.com/duke-git/lancet/blob/main/compare/compare.go)
- [https://github.com/duke-git/lancet/blob/main/compare/compare_internal.go](https://github.com/duke-git/lancet/blob/main/compare/compare_internal.go)
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/v2/condition"
)
```
<div STYLE="page-break-after: always;"></div>
## 目录
- [Equal](#Equal)
- [EqualValue](#EqualValue)
- [LessThan](#LessThan)
- [GreaterThan](#GreaterThan)
- [LessOrEqual](#LessOrEqual)
- [GreaterOrEqual](#GreaterOrEqual)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="Equal">Equal</span>
<p>检查两个值是否相等(检查类型和值)</p>
<b>函数签名:</b>
```go
func Equal(left, right any) bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.Equal(1, 1)
result2 := compare.Equal("1", "1")
result3 := compare.Equal([]int{1, 2, 3}, []int{1, 2, 3})
result4 := compare.Equal(map[int]string{1: "a", 2: "b"}, map[int]string{1: "a", 2: "b"})
result5 := compare.Equal(1, "1")
result6 := compare.Equal(1, int64(1))
result7 := compare.Equal([]int{1, 2}, []int{1, 2, 3})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
// Output:
// true
// true
// true
// true
// false
// false
// false
}
```
### <span id="EqualValue">EqualValue</span>
<p>检查两个值是否相等(只检查值)</p>
<b>函数签名:</b>
```go
func EqualValue(left, right any) bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.EqualValue(1, 1)
result2 := compare.EqualValue(int(1), int64(1))
result3 := compare.EqualValue(1, "1")
result4 := compare.EqualValue(1, "2")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// true
// true
// false
}
```
### <span id="LessThan">LessThan</span>
<p>验证参数`left`的值是否小于参数`right`的值。</p>
<b>函数签名:</b>
```go
func LessThan(left, right any) bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.LessThan(1, 2)
result2 := compare.LessThan(1.1, 2.2)
result3 := compare.LessThan("a", "b")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := compare.LessThan(time1, time2)
result5 := compare.LessThan(2, 1)
result6 := compare.LessThan(1, int64(2))
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
// Output:
// true
// true
// true
// true
// false
// false
}
```
### <span id="GreaterThan">GreaterThan</span>
<p>验证参数`left`的值是否大于参数`right`的值。</p>
<b>函数签名:</b>
```go
func GreaterThan(left, right any) bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.GreaterThan(2, 1)
result2 := compare.GreaterThan(2.2, 1.1)
result3 := compare.GreaterThan("b", "a")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := compare.GreaterThan(time2, time1)
result5 := compare.GreaterThan(1, 2)
result6 := compare.GreaterThan(int64(2), 1)
result7 := compare.GreaterThan("b", "c")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
// Output:
// true
// true
// true
// true
// false
// false
// false
}
```
### <span id="LessOrEqual">LessOrEqual</span>
<p>验证参数`left`的值是否小于或等于参数`right`的值。</p>
<b>函数签名:</b>
```go
func LessOrEqual(left, right any) bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.LessOrEqual(1, 1)
result2 := compare.LessOrEqual(1.1, 2.2)
result3 := compare.LessOrEqual("a", "b")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := compare.LessOrEqual(time1, time2)
result5 := compare.LessOrEqual(2, 1)
result6 := compare.LessOrEqual(1, int64(2))
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
// Output:
// true
// true
// true
// true
// false
// false
}
```
### <span id="GreaterOrEqual">GreaterOrEqual</span>
<p>验证参数`left`的值是否大于或参数`right`的值。</p>
<b>函数签名:</b>
```go
func GreaterOrEqual(left, right any) bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/compare"
)
func main() {
result1 := compare.GreaterOrEqual(1, 1)
result2 := compare.GreaterOrEqual(2.2, 1.1)
result3 := compare.GreaterOrEqual("b", "b")
time1 := time.Now()
time2 := time1.Add(time.Second)
result4 := compare.GreaterOrEqual(time2, time1)
result5 := compare.GreaterOrEqual(1, 2)
result6 := compare.GreaterOrEqual(int64(2), 1)
result7 := compare.GreaterOrEqual("b", "c")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
// Output:
// true
// true
// true
// true
// false
// false
// false
}
```

View File

@@ -1,5 +1,5 @@
# Concurrency
Package concurrency contain some functions to support concurrent programming. eg, goroutine, channel, async.
Package concurrency contain some functions to support concurrent programming. eg, goroutine, channel.
<div STYLE="page-break-after: always;"></div>

View File

@@ -1,5 +1,5 @@
# Concurrency
并发包包含一些支持并发编程的功能。例如goroutine, channel, async等。
并发包包含一些支持并发编程的功能。例如goroutine, channel等。
<div STYLE="page-break-after: always;"></div>

View File

@@ -40,6 +40,7 @@ import (
- [DecodeByte](#DecodeByte)
- [DeepClone](#DeepClone)
- [CopyProperties](#CopyProperties)
- [ToInterface](#ToInterface)
<div STYLE="page-break-after: always;"></div>
@@ -629,7 +630,6 @@ func main() {
}
```
### <span id="DeepClone">DeepClone</span>
<p>Creates a deep copy of passed item, can't clone unexported field of struct.</p>
@@ -694,10 +694,9 @@ func main() {
}
```
### <span id="CopyProperties">CopyProperties</span>
<p>Copies each field from the source struct into the destination struct.</p>
<p>Copies each field from the source struct into the destination struct. Use json.Marshal/Unmarshal, so json tag should be set for fields of dst and src struct.</p>
<b>Signature:</b>
@@ -716,44 +715,95 @@ import (
)
func main() {
type Address struct {
Country string
ZipCode string
type Disk struct {
Name string `json:"name"`
Total string `json:"total"`
Used string `json:"used"`
Percent float64 `json:"percent"`
}
type User struct {
Name string
Age int
Role string
Addr Address
Hobbys []string
salary int
type DiskVO struct {
Name string `json:"name"`
Total string `json:"total"`
Used string `json:"used"`
Percent float64 `json:"percent"`
}
type Employee struct {
Name string
Age int
Role string
Addr Address
Hobbys []string
salary int
type Indicator struct {
Id string `json:"id"`
Ip string `json:"ip"`
UpTime string `json:"upTime"`
LoadAvg string `json:"loadAvg"`
Cpu int `json:"cpu"`
Disk []Disk `json:"disk"`
Stop chan bool `json:"-"`
}
user := User{Name: "user001", Age: 10, Role: "Admin", Addr: Address{Country: "CN", ZipCode: "001"}, Hobbys: []string{"a", "b"}, salary: 1000}
type IndicatorVO struct {
Id string `json:"id"`
Ip string `json:"ip"`
UpTime string `json:"upTime"`
LoadAvg string `json:"loadAvg"`
Cpu int64 `json:"cpu"`
Disk []DiskVO `json:"disk"`
}
employee1 := Employee{}
CopyProperties(&employee1, &user)
indicator := &Indicator{Id: "001", Ip: "127.0.0.1", Cpu: 1, Disk: []Disk{
{Name: "disk-001", Total: "100", Used: "1", Percent: 10},
{Name: "disk-002", Total: "200", Used: "1", Percent: 20},
{Name: "disk-003", Total: "300", Used: "1", Percent: 30},
}}
employee2 := Employee{Name: "employee001", Age: 20, Role: "User",
Addr: Address{Country: "UK", ZipCode: "002"}, salary: 500}
indicatorVO := IndicatorVO{}
CopyProperties(&employee2, &user)
err := convertor.CopyProperties(&indicatorVO, indicator)
fmt.Println(employee1)
fmt.Println(employee2)
if err != nil {
return
}
fmt.Println(indicatorVO.Id)
fmt.Println(indicatorVO.Ip)
fmt.Println(len(indicatorVO.Disk))
// Output:
// {user001 10 Admin {CN 001} [a b] 0}
// {user001 10 Admin {CN 001} [a b] 500}
// 001
// 127.0.0.1
// 3
}
```
### <span id="ToInterface">ToInterface</span>
<p>Converts reflect value to its interface type.</p>
<b>Signature:</b>
```go
func ToInterface(v reflect.Value) (value interface{}, ok bool)
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/convertor"
)
func main() {
val := reflect.ValueOf("abc")
iVal, ok := convertor.ToInterface(val)
fmt.Printf("%T\n", iVal)
fmt.Printf("%v\n", iVal)
fmt.Println(ok)
// Output:
// string
// abc
// true
}
```

View File

@@ -40,7 +40,7 @@ import (
- [DecodeByte](#DecodeByte)
- [DeepClone](#DeepClone)
- [CopyProperties](#CopyProperties)
- [ToInterface](#ToInterface)
<div STYLE="page-break-after: always;"></div>
@@ -696,7 +696,7 @@ func main() {
### <span id="CopyProperties">CopyProperties</span>
<p>拷贝不同结构体之间的同名字段。</p>
<p>拷贝不同结构体之间的同名字段。使用json.Marshal序列化需要设置dst和src struct字段的json tag。</p>
<b>函数签名:</b>
@@ -715,44 +715,95 @@ import (
)
func main() {
type Address struct {
Country string
ZipCode string
type Disk struct {
Name string `json:"name"`
Total string `json:"total"`
Used string `json:"used"`
Percent float64 `json:"percent"`
}
type User struct {
Name string
Age int
Role string
Addr Address
Hobbys []string
salary int
type DiskVO struct {
Name string `json:"name"`
Total string `json:"total"`
Used string `json:"used"`
Percent float64 `json:"percent"`
}
type Employee struct {
Name string
Age int
Role string
Addr Address
Hobbys []string
salary int
type Indicator struct {
Id string `json:"id"`
Ip string `json:"ip"`
UpTime string `json:"upTime"`
LoadAvg string `json:"loadAvg"`
Cpu int `json:"cpu"`
Disk []Disk `json:"disk"`
Stop chan bool `json:"-"`
}
user := User{Name: "user001", Age: 10, Role: "Admin", Addr: Address{Country: "CN", ZipCode: "001"}, Hobbys: []string{"a", "b"}, salary: 1000}
type IndicatorVO struct {
Id string `json:"id"`
Ip string `json:"ip"`
UpTime string `json:"upTime"`
LoadAvg string `json:"loadAvg"`
Cpu int64 `json:"cpu"`
Disk []DiskVO `json:"disk"`
}
employee1 := Employee{}
CopyProperties(&employee1, &user)
indicator := &Indicator{Id: "001", Ip: "127.0.0.1", Cpu: 1, Disk: []Disk{
{Name: "disk-001", Total: "100", Used: "1", Percent: 10},
{Name: "disk-002", Total: "200", Used: "1", Percent: 20},
{Name: "disk-003", Total: "300", Used: "1", Percent: 30},
}}
employee2 := Employee{Name: "employee001", Age: 20, Role: "User",
Addr: Address{Country: "UK", ZipCode: "002"}, salary: 500}
indicatorVO := IndicatorVO{}
CopyProperties(&employee2, &user)
err := convertor.CopyProperties(&indicatorVO, indicator)
fmt.Println(employee1)
fmt.Println(employee2)
if err != nil {
return
}
fmt.Println(indicatorVO.Id)
fmt.Println(indicatorVO.Ip)
fmt.Println(len(indicatorVO.Disk))
// Output:
// {user001 10 Admin {CN 001} [a b] 0}
// {user001 10 Admin {CN 001} [a b] 500}
// 001
// 127.0.0.1
// 3
}
```
```
### <span id="ToInterface">ToInterface</span>
<p>将反射值转换成对应的interface类型。</p>
<b>函数签名:</b>
```go
func ToInterface(v reflect.Value) (value interface{}, ok bool)
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/convertor"
)
func main() {
val := reflect.ValueOf("abc")
iVal, ok := convertor.ToInterface(val)
fmt.Printf("%T\n", iVal)
fmt.Printf("%v\n", iVal)
fmt.Println(ok)
// Output:
// string
// abc
// true
}
```

View File

@@ -1,16 +1,17 @@
# Set
Set is a data container, like list, but elements of set is not duplicate.
<div STYLE="page-break-after: always;"></div>
## Source
- [https://github.com/duke-git/lancet/blob/main/datastructure/set/set.go](https://github.com/duke-git/lancet/blob/main/datastructure/set/set.go)
- [https://github.com/duke-git/lancet/blob/main/datastructure/set/set.go](https://github.com/duke-git/lancet/blob/main/datastructure/set/set.go)
<div STYLE="page-break-after: always;"></div>
## Usage
```go
import (
set "github.com/duke-git/lancet/v2/datastructure/set"
@@ -21,32 +22,32 @@ import (
## Index
- [NewSet](#NewSet)
- [NewSetFromSlice](#NewSetFromSlice)
- [Values](#Values)
- [Add](#Add)
- [AddIfNotExist](#AddIfNotExist)
- [AddIfNotExistBy](#AddIfNotExistBy)
- [Delete](#Delete)
- [Contain](#Contain)
- [ContainAll](#ContainAll)
- [Clone](#Clone)
- [Size](#Size)
- [Equal](#Equal)
- [Iterate](#Iterate)
- [IsEmpty](#IsEmpty)
- [Union](#Union)
- [Intersection](#Intersection)
- [SymmetricDifference](#SymmetricDifference)
- [Minus](#Minus)
- [NewSet](#NewSet)
- [NewSetFromSlice](#NewSetFromSlice)
- [Values](#Values)
- [Add](#Add)
- [AddIfNotExist](#AddIfNotExist)
- [AddIfNotExistBy](#AddIfNotExistBy)
- [Delete](#Delete)
- [Contain](#Contain)
- [ContainAll](#ContainAll)
- [Clone](#Clone)
- [Size](#Size)
- [Equal](#Equal)
- [Iterate](#Iterate)
- [EachWithBreak](#EachWithBreak)
- [IsEmpty](#IsEmpty)
- [Union](#Union)
- [Intersection](#Intersection)
- [SymmetricDifference](#SymmetricDifference)
- [Minus](#Minus)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="NewSet">NewSet</span>
<p>Create a set instance</p>
<b>Signature:</b>
@@ -55,6 +56,7 @@ import (
type Set[T comparable] map[T]bool
func NewSet[T comparable](items ...T) Set[T]
```
<b>Example:</b>
```go
@@ -71,8 +73,8 @@ func main() {
}
```
### <span id="NewSetFromSlice">NewSetFromSlice</span>
<p>Create a set from slice</p>
<b>Signature:</b>
@@ -80,6 +82,7 @@ func main() {
```go
func NewSetFromSlice[T comparable](items []T) Set[T]
```
<b>Example:</b>
```go
@@ -96,9 +99,8 @@ func main() {
}
```
### <span id="Values">Values</span>
<p>Return slice of all set data</p>
<b>Signature:</b>
@@ -106,6 +108,7 @@ func main() {
```go
func (s Set[T]) Values() []T
```
<b>Example:</b>
```go
@@ -122,10 +125,8 @@ func main() {
}
```
### <span id="Add">Add</span>
<p>Add items to set</p>
<b>Signature:</b>
@@ -133,6 +134,7 @@ func main() {
```go
func (s Set[T]) Add(items ...T)
```
<b>Example:</b>
```go
@@ -151,8 +153,8 @@ func main() {
}
```
### <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>
@@ -160,6 +162,7 @@ func main() {
```go
func (s Set[T]) AddIfNotExist(item T) bool
```
<b>Example:</b>
```go
@@ -175,7 +178,7 @@ func main() {
st.Add(1, 2, 3)
r1 := st.AddIfNotExist(1)
r2 := st.AddIfNotExist(4)
r2 := st.AddIfNotExist(4)
fmt.Println(r1) // false
fmt.Println(r2) // true
@@ -183,8 +186,8 @@ func main() {
}
```
### <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>
@@ -192,6 +195,7 @@ func main() {
```go
func (s Set[T]) AddIfNotExistBy(item T, checker func(element T) bool) bool
```
<b>Example:</b>
```go
@@ -206,23 +210,23 @@ func main() {
st := set.NewSet[int]()
st.Add(1, 2)
ok := st.AddIfNotExistBy(3, func(val int) bool {
return val%2 != 0
})
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
})
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>
@@ -230,6 +234,7 @@ func main() {
```go
func (s Set[T]) Delete(items ...T)
```
<b>Example:</b>
```go
@@ -249,9 +254,8 @@ func main() {
}
```
### <span id="Contain">Contain</span>
<p>Check if item is in set or not</p>
<b>Signature:</b>
@@ -259,6 +263,7 @@ func main() {
```go
func (s Set[T]) Contain(item T) bool
```
<b>Example:</b>
```go
@@ -278,10 +283,8 @@ func main() {
}
```
### <span id="ContainAll">ContainAll</span>
<p>Checks if set contains another set</p>
<b>Signature:</b>
@@ -289,6 +292,7 @@ func main() {
```go
func (s Set[T]) ContainAll(other Set[T]) bool
```
<b>Example:</b>
```go
@@ -301,17 +305,16 @@ import (
func main() {
set1 := set.NewSet(1, 2, 3)
set2 := set.NewSet(1, 2)
set3 := set.NewSet(1, 2, 3, 4)
set2 := set.NewSet(1, 2)
set3 := set.NewSet(1, 2, 3, 4)
fmt.Println(set1.ContainAll(set2)) //true
fmt.Println(set1.ContainAll(set3)) //false
}
```
### <span id="Size">Size</span>
<p>Get the number of elements in set</p>
<b>Signature:</b>
@@ -319,6 +322,7 @@ func main() {
```go
func (s Set[T]) Size() int
```
<b>Example:</b>
```go
@@ -336,9 +340,8 @@ func main() {
}
```
### <span id="Clone">Clone</span>
<p>Make a copy of set</p>
<b>Signature:</b>
@@ -346,6 +349,7 @@ func main() {
```go
func (s Set[T]) Clone() Set[T]
```
<b>Example:</b>
```go
@@ -365,10 +369,8 @@ func main() {
}
```
### <span id="Equal">Equal</span>
<p>Check if two sets has same elements or not</p>
<b>Signature:</b>
@@ -376,6 +378,7 @@ func main() {
```go
func (s Set[T]) Equal(other Set[T]) bool
```
<b>Example:</b>
```go
@@ -396,9 +399,8 @@ func main() {
}
```
### <span id="Iterate">Iterate</span>
<p>Call function by every element of set</p>
<b>Signature:</b>
@@ -406,6 +408,7 @@ func main() {
```go
func (s Set[T]) Iterate(fn func(item T))
```
<b>Example:</b>
```go
@@ -427,9 +430,45 @@ func main() {
}
```
### <span id="EachWithBreak">EachWithBreak</span>
<p>Iterates over elements of a set and invokes function for each element, when iteratee return false, will break the for each loop.</p>
<b>Signature:</b>
```go
func (s Set[T]) EachWithBreak(iteratee func(item T) bool)
```
<b>Example:</b>
```go
package main
import (
"fmt"
set "github.com/duke-git/lancet/v2/datastructure/set"
)
func main() {
s := set.NewSet(1, 2, 3, 4, 5)
var sum int
s.EachWithBreak(func(n int) bool {
if n > 3 {
return false
}
sum += n
return true
})
fmt.Println(sum) //6
}
```
### <span id="IsEmpty">IsEmpty</span>
<p>Check if the set is empty or not</p>
<b>Signature:</b>
@@ -437,6 +476,7 @@ func main() {
```go
func (s Set[T]) IsEmpty() bool
```
<b>Example:</b>
```go
@@ -456,9 +496,8 @@ func main() {
}
```
### <span id="Union">Union</span>
<p>Create a new set contain all element of set s and other</p>
<b>Signature:</b>
@@ -466,6 +505,7 @@ func main() {
```go
func (s Set[T]) Union(other Set[T]) Set[T]
```
<b>Example:</b>
```go
@@ -485,9 +525,8 @@ func main() {
}
```
### <span id="Intersection">Intersection</span>
<p>Create a new set whose element both be contained in set s and other</p>
<b>Signature:</b>
@@ -495,6 +534,7 @@ func main() {
```go
func (s Set[T]) Intersection(other Set[T]) Set[T]
```
<b>Example:</b>
```go
@@ -514,11 +554,8 @@ func main() {
}
```
### <span id="SymmetricDifference">SymmetricDifference</span>
<p>Create a new set whose element is in set1 or set2, but not in both set1 and set2</p>
<b>Signature:</b>
@@ -526,6 +563,7 @@ func main() {
```go
func (s Set[T]) SymmetricDifference(other Set[T]) Set[T]
```
<b>Example:</b>
```go
@@ -538,18 +576,15 @@ import (
func main() {
set1 := set.NewSet(1, 2, 3)
set2 := set.NewSet(2, 3, 4, 5)
set3 := set1.SymmetricDifference(set2)
set2 := set.NewSet(2, 3, 4, 5)
set3 := set1.SymmetricDifference(set2)
fmt.Println(set3.Values()) //1,4,5
}
```
### <span id="Minus">Minus</span>
<p>Create an set of whose element in origin set but not in compared set</p>
<b>Signature:</b>
@@ -557,6 +592,7 @@ func main() {
```go
func (s Set[T]) Minus(comparedSet Set[T]) Set[T]
```
<b>Example:</b>
```go
@@ -569,8 +605,8 @@ import (
func main() {
set1 := set.NewSet(1, 2, 3)
set2 := set.NewSet(2, 3, 4, 5)
set3 := set.NewSet(2, 3)
set2 := set.NewSet(2, 3, 4, 5)
set3 := set.NewSet(2, 3)
res1 := set1.Minus(set2)
fmt.Println(res1.Values()) //1
@@ -580,5 +616,35 @@ func main() {
}
```
### <span id="Pop">Pop</span>
<p>Delete the top element of set then return it, if set is empty, return nil-value of T and false.</p>
<b>Signature:</b>
```go
func (s Set[T]) Pop() (v T, ok bool)
```
<b>Example:</b>
```go
package main
import (
"fmt"
set "github.com/duke-git/lancet/v2/datastructure/set"
)
func main() {
s := set.NewSet[int]()
s.Add(1)
s.Add(2)
s.Add(3)
val, ok = s.Pop()
fmt.Println(val) // 3
fmt.Println(ok) // true
}
```

View File

@@ -1,16 +1,17 @@
# Set
Set集合数据结构类似列表。Set中元素不重复。
Set 集合数据结构类似列表。Set 中元素不重复。
<div STYLE="page-break-after: always;"></div>
## 源码
- [https://github.com/duke-git/lancet/blob/main/datastructure/set/set.go](https://github.com/duke-git/lancet/blob/main/datastructure/set/set.go)
- [https://github.com/duke-git/lancet/blob/main/datastructure/set/set.go](https://github.com/duke-git/lancet/blob/main/datastructure/set/set.go)
<div STYLE="page-break-after: always;"></div>
## 用法
```go
import (
set "github.com/duke-git/lancet/v2/datastructure/set"
@@ -21,32 +22,31 @@ import (
## 目录
- [NewSet](#NewSet)
- [NewSetFromSlice](#NewSetFromSlice)
- [Values](#Values)
- [Add](#Add)
- [AddIfNotExist](#AddIfNotExist)
- [AddIfNotExistBy](#AddIfNotExistBy)
- [Delete](#Delete)
- [Contain](#Contain)
- [ContainAll](#ContainAll)
- [Clone](#Clone)
- [Size](#Size)
- [Equal](#Equal)
- [Iterate](#Iterate)
- [IsEmpty](#IsEmpty)
- [Union](#Union)
- [Intersection](#Intersection)
- [SymmetricDifference](#SymmetricDifference)
- [Minus](#Minus)
- [NewSet](#NewSet)
- [NewSetFromSlice](#NewSetFromSlice)
- [Values](#Values)
- [Add](#Add)
- [AddIfNotExist](#AddIfNotExist)
- [AddIfNotExistBy](#AddIfNotExistBy)
- [Delete](#Delete)
- [Contain](#Contain)
- [ContainAll](#ContainAll)
- [Clone](#Clone)
- [Size](#Size)
- [Equal](#Equal)
- [Iterate](#Iterate)
- [IsEmpty](#IsEmpty)
- [Union](#Union)
- [Intersection](#Intersection)
- [SymmetricDifference](#SymmetricDifference)
- [Minus](#Minus)
<div STYLE="page-break-after: always;"></div>
## 文档
### <span id="NewSet">NewSet</span>
<p>返回Set结构体对象</p>
<b>函数签名:</b>
@@ -55,6 +55,7 @@ import (
type Set[T comparable] map[T]bool
func NewSet[T comparable](items ...T) Set[T]
```
<b>示例:</b>
```go
@@ -71,9 +72,8 @@ func main() {
}
```
### <span id="NewSetFromSlice">NewSetFromSlice</span>
<p>基于切片创建集合</p>
<b>函数签名:</b>
@@ -81,6 +81,7 @@ func main() {
```go
func NewSetFromSlice[T comparable](items []T) Set[T]
```
<b>示例:</b>
```go
@@ -97,9 +98,8 @@ func main() {
}
```
### <span id="Values">Values</span>
<p>获取集合中所有元素的切片</p>
<b>函数签名:</b>
@@ -107,6 +107,7 @@ func main() {
```go
func (s Set[T]) Values() []T
```
<b>示例:</b>
```go
@@ -123,10 +124,8 @@ func main() {
}
```
### <span id="Add">Add</span>
<p>向集合中添加元素</p>
<b>函数签名:</b>
@@ -134,6 +133,7 @@ func main() {
```go
func (s Set[T]) Add(items ...T)
```
<b>示例:</b>
```go
@@ -152,8 +152,8 @@ func main() {
}
```
### <span id="AddIfNotExist">AddIfNotExist</span>
<p>如果集合中不存在元素则添加该元素返回true, 如果集合中存在元素, 不做任何操作返回false</p>
<b>函数签名:</b>
@@ -161,6 +161,7 @@ func main() {
```go
func (s Set[T]) AddIfNotExist(item T) bool
```
<b>示例:</b>
```go
@@ -176,7 +177,7 @@ func main() {
st.Add(1, 2, 3)
r1 := st.AddIfNotExist(1)
r2 := st.AddIfNotExist(4)
r2 := st.AddIfNotExist(4)
fmt.Println(r1) // false
fmt.Println(r2) // true
@@ -184,8 +185,8 @@ func main() {
}
```
### <span id="AddIfNotExistBy">AddIfNotExistBy</span>
<p>根据checker函数判断元素是否在集合中如果集合中不存在元素且checker返回true则添加该元素返回true, 否则不做任何操作返回false</p>
<b>函数签名:</b>
@@ -193,6 +194,7 @@ func main() {
```go
func (s Set[T]) AddIfNotExistBy(item T, checker func(element T) bool) bool
```
<b>示例:</b>
```go
@@ -207,24 +209,23 @@ func main() {
st := set.NewSet[int]()
st.Add(1, 2)
ok := st.AddIfNotExistBy(3, func(val int) bool {
return val%2 != 0
})
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
})
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>
<b>函数签名:</b>
@@ -232,6 +233,7 @@ func main() {
```go
func (s Set[T]) Delete(items ...T)
```
<b>示例:</b>
```go
@@ -251,9 +253,8 @@ func main() {
}
```
### <span id="Contain">Contain</span>
<p>判断集合是否包含某个值</p>
<b>函数签名:</b>
@@ -261,6 +262,7 @@ func main() {
```go
func (s Set[T]) Contain(item T) bool
```
<b>示例:</b>
```go
@@ -280,10 +282,8 @@ func main() {
}
```
### <span id="ContainAll">ContainAll</span>
<p>判断集合是否包含另一个集合</p>
<b>函数签名:</b>
@@ -291,6 +291,7 @@ func main() {
```go
func (s Set[T]) ContainAll(other Set[T]) bool
```
<b>示例:</b>
```go
@@ -303,17 +304,16 @@ import (
func main() {
set1 := set.NewSet(1, 2, 3)
set2 := set.NewSet(1, 2)
set3 := set.NewSet(1, 2, 3, 4)
set2 := set.NewSet(1, 2)
set3 := set.NewSet(1, 2, 3, 4)
fmt.Println(set1.ContainAll(set2)) //true
fmt.Println(set1.ContainAll(set3)) //false
}
```
### <span id="Size">Size</span>
<p>获取集合中元素的个数</p>
<b>函数签名:</b>
@@ -321,6 +321,7 @@ func main() {
```go
func (s Set[T]) Size() int
```
<b>示例:</b>
```go
@@ -338,9 +339,8 @@ func main() {
}
```
### <span id="Clone">Clone</span>
<p>克隆一个集合</p>
<b>函数签名:</b>
@@ -348,6 +348,7 @@ func main() {
```go
func (s Set[T]) Clone() Set[T]
```
<b>示例:</b>
```go
@@ -367,10 +368,8 @@ func main() {
}
```
### <span id="Equal">Equal</span>
<p>比较两个集合是否相等,包含相同元素为相等</p>
<b>函数签名:</b>
@@ -378,6 +377,7 @@ func main() {
```go
func (s Set[T]) Equal(other Set[T]) bool
```
<b>示例:</b>
```go
@@ -398,9 +398,8 @@ func main() {
}
```
### <span id="Iterate">Iterate</span>
<p>迭代结合,在每个元素上调用函数</p>
<b>函数签名:</b>
@@ -408,6 +407,7 @@ func main() {
```go
func (s Set[T]) Iterate(fn func(item T))
```
<b>示例:</b>
```go
@@ -429,9 +429,45 @@ func main() {
}
```
### <span id="EachWithBreak">EachWithBreak</span>
<p>遍历集合的元素并为每个元素调用iteratee函数当iteratee函数返回false时终止遍历。</p>
<b>函数签名:</b>
```go
func (s Set[T]) EachWithBreak(iteratee func(item T) bool)
```
<b>示例:</b>
```go
package main
import (
"fmt"
set "github.com/duke-git/lancet/v2/datastructure/set"
)
func main() {
s := set.NewSet(1, 2, 3, 4, 5)
var sum int
s.EachWithBreak(func(n int) bool {
if n > 3 {
return false
}
sum += n
return true
})
fmt.Println(sum) //6
}
```
### <span id="IsEmpty">IsEmpty</span>
<p>判断集合是否为空</p>
<b>函数签名:</b>
@@ -439,6 +475,7 @@ func main() {
```go
func (s Set[T]) IsEmpty() bool
```
<b>示例:</b>
```go
@@ -458,9 +495,8 @@ func main() {
}
```
### <span id="Union">Union</span>
<p>求两个集合的并集</p>
<b>函数签名:</b>
@@ -468,6 +504,7 @@ func main() {
```go
func (s Set[T]) Union(other Set[T]) Set[T]
```
<b>示例:</b>
```go
@@ -487,9 +524,8 @@ func main() {
}
```
### <span id="Intersection">Intersection</span>
<p>求两个集合的交集</p>
<b>函数签名:</b>
@@ -497,6 +533,7 @@ func main() {
```go
func (s Set[T]) Intersection(other Set[T]) Set[T]
```
<b>示例:</b>
```go
@@ -516,8 +553,8 @@ func main() {
}
```
### <span id="SymmetricDifference">SymmetricDifference</span>
<p>返回一个集合,其中元素在第一个集合或第二个集合中,且不同时存在于两个集合中</p>
<b>函数签名:</b>
@@ -525,6 +562,7 @@ func main() {
```go
func (s Set[T]) SymmetricDifference(other Set[T]) Set[T]
```
<b>示例:</b>
```go
@@ -537,18 +575,15 @@ import (
func main() {
set1 := set.NewSet(1, 2, 3)
set2 := set.NewSet(2, 3, 4, 5)
set3 := set1.SymmetricDifference(set2)
set2 := set.NewSet(2, 3, 4, 5)
set3 := set1.SymmetricDifference(set2)
fmt.Println(set3.Values()) //1,4,5
}
```
### <span id="Minus">Minus</span>
<p>创建一个集合,其元素在原始集中但不在比较集中</p>
<b>函数签名:</b>
@@ -556,6 +591,7 @@ func main() {
```go
func (s Set[T]) Minus(comparedSet Set[T]) Set[T]
```
<b>示例:</b>
```go
@@ -568,8 +604,8 @@ import (
func main() {
set1 := set.NewSet(1, 2, 3)
set2 := set.NewSet(2, 3, 4, 5)
set3 := set.NewSet(2, 3)
set2 := set.NewSet(2, 3, 4, 5)
set3 := set.NewSet(2, 3)
res1 := set1.Minus(set2)
fmt.Println(res1.Values()) //1
@@ -579,5 +615,35 @@ func main() {
}
```
### <span id="Pop">Pop</span>
<p>删除并返回集合中的顶部元素</p>
<b>函数签名:</b>
```go
func (s Set[T]) Pop() (v T, ok bool)
```
<b>示例:</b>
```go
package main
import (
"fmt"
set "github.com/duke-git/lancet/v2/datastructure/set"
)
func main() {
s := set.NewSet[int]()
s.Add(1)
s.Add(2)
s.Add(3)
val, ok = s.Pop()
fmt.Println(val) // 3
fmt.Println(ok) // true
}
```

View File

@@ -26,6 +26,7 @@ import (
- [AddDay](#AddDay)
- [AddHour](#AddHour)
- [AddMinute](#AddMinute)
- [AddYear](#AddYear)
- [BeginOfMinute](#BeginOfMinute)
- [BeginOfHour](#BeginOfHour)
- [BeginOfDay](#BeginOfDay)
@@ -53,6 +54,7 @@ import (
- [ToFormat](#ToFormat)
- [ToFormatForTpl](#ToFormatForTpl)
- [ToIso8601](#ToIso8601)
- [IsLeapYear](#IsLeapYear)
<div STYLE="page-break-after: always;"></div>
@@ -198,6 +200,45 @@ func main() {
}
```
### <span id="AddYear">AddYear</span>
<p>Add or sub year to the time.</p>
<b>Signature:</b>
```go
func AddYear(t time.Time, year int64) time.Time
```
<b>Example:</b>
```go
package main
import (
"fmt"
"time"
"github.com/duke-git/lancet/v2/datetime"
)
func main() {
now := time.Now()
after1Year := AddYear(now, 1)
diff1 := after1Year.Sub(now)
before1Year := AddYear(now, -1)
diff2 := before1Year.Sub(now)
fmt.Println(diff1)
fmt.Println(diff2)
// Output:
// 8760h0m0s
// -8760h0m0s
}
```
### <span id="BeginOfMinute">BeginOfMinute</span>
<p>Return beginning minute time of day.</p>
@@ -607,8 +648,8 @@ func main() {
now := time.Now()
currentDate := datetime.GetNowDate()
fmt.Println(currentDate)
fmt.Println(currentDate)
// Output:
// 2022-01-28
}
@@ -671,8 +712,8 @@ func main() {
now := time.Now()
current := datetime.GetNowDateTime()
fmt.Println(current)
fmt.Println(current)
// Output:
// 2022-01-28 15:59:33
}
@@ -702,9 +743,9 @@ import (
func main() {
now := time.Now()
zeroTime := datetime.GetZeroHourTimestamp()
fmt.Println(zeroTime)
fmt.Println(zeroTime)
// Output:
// 1643299200
}
@@ -735,8 +776,8 @@ func main() {
now := time.Now()
nightTime := datetime.GetNightTimestamp()
fmt.Println(nightTime)
fmt.Println(nightTime)
// Output:
// 1643385599
}
@@ -842,8 +883,8 @@ import (
func main() {
tm := datetime.NewUnixNow()
fmt.Println(tm)
fmt.Println(tm)
// Output:
// &{1647597438}
}
@@ -874,8 +915,8 @@ import (
func main() {
tm := datetime.NewUnix(1647597438)
fmt.Println(tm)
fmt.Println(tm)
// Output:
// &{1647597438}
}
@@ -906,8 +947,8 @@ import (
func main() {
tm, err := datetime.NewFormat("2022-03-18 17:04:05")
fmt.Println(tm)
fmt.Println(tm)
// Output:
// &{1647594245}
}
@@ -938,8 +979,8 @@ import (
func main() {
tm, err := datetime.NewISO8601("2006-01-02T15:04:05.999Z")
fmt.Println(tm)
fmt.Println(tm)
// Output:
// &{1136214245}
}
@@ -967,8 +1008,8 @@ import (
func main() {
tm := datetime.NewUnixNow()
fmt.Println(tm.ToUnix())
fmt.Println(tm.ToUnix())
// Output:
// 1647597438
}
@@ -996,8 +1037,8 @@ import (
func main() {
tm, _ := datetime.NewFormat("2022-03-18 17:04:05")
fmt.Println(tm.ToFormat())
fmt.Println(tm.ToFormat())
// Output:
// 2022-03-18 17:04:05
}
@@ -1026,8 +1067,8 @@ import (
func main() {
tm, _ := datetime.NewFormat("2022-03-18 17:04:05")
ts := tm.ToFormatForTpl("2006/01/02 15:04:05")
fmt.Println(ts)
fmt.Println(ts)
// Output:
// 2022/03/18 17:04:05
}
@@ -1056,9 +1097,42 @@ import (
func main() {
tm, _ := datetime.NewISO8601("2006-01-02T15:04:05.999Z")
ts := tm.ToIso8601()
fmt.Println(ts)
fmt.Println(ts)
// Output:
// 2006-01-02T23:04:05+08:00
}
```
### <span id="IsLeapYear">IsLeapYear</span>
<p>check if param `year` is leap year or not.</p>
<b>Signature:</b>
```go
func IsLeapYear(year int) bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/datetime"
)
func main() {
result1 := datetime.IsLeapYear(2000)
result2 := datetime.IsLeapYear(2001)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```

View File

@@ -1,15 +1,17 @@
# Datetime
datetime日期时间处理包格式化日期比较日期。
datetime 日期时间处理包,格式化日期,比较日期。
<div STYLE="page-break-after: always;"></div>
## 源码:
- [https://github.com/duke-git/lancet/blob/main/datetime/datetime.go](https://github.com/duke-git/lancet/blob/main/datetime/datetime.go)
- [https://github.com/duke-git/lancet/blob/main/datetime/datetime.go](https://github.com/duke-git/lancet/blob/main/datetime/datetime.go)
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/v2/datetime"
@@ -19,74 +21,78 @@ import (
<div STYLE="page-break-after: always;"></div>
## 目录
- [AddDay](#AddDay)
- [AddHour](#AddHour)
- [AddMinute](#AddMinute)
- [BeginOfMinute](#BeginOfMinute)
- [BeginOfHour](#BeginOfHour)
- [BeginOfDay](#BeginOfDay)
- [BeginOfWeek](#BeginOfWeek)
- [BeginOfMonth](#BeginOfMonth)
- [BeginOfYear](#BeginOfYear)
- [EndOfMinute](#EndOfMinute)
- [EndOfHour](#EndOfHour)
- [EndOfDay](#EndOfDay)
- [EndOfWeek](#EndOfWeek)
- [EndOfMonth](#EndOfMonth)
- [EndOfYear](#EndOfYear)
- [GetNowDate](#GetNowDate)
- [GetNowTime](#GetNowTime)
- [GetNowDateTime](#GetNowDateTime)
- [GetZeroHourTimestamp](#GetZeroHourTimestamp)
- [GetNightTimestamp](#GetNightTimestamp)
- [FormatTimeToStr](#FormatTimeToStr)
- [FormatStrToTime](#FormatStrToTime)
- [NewUnixNow](#NewUnixNow)
- [NewUnix](#NewUnix)
- [NewFormat](#NewFormat)
- [NewISO8601](#NewISO8601)
- [ToUnix](#ToUnix)
- [ToFormat](#ToFormat)
- [ToFormatForTpl](#ToFormatForTpl)
- [ToIso8601](#ToIso8601)
- [AddDay](#AddDay)
- [AddHour](#AddHour)
- [AddMinute](#AddMinute)
- [AddYear](#AddYear)
- [BeginOfMinute](#BeginOfMinute)
- [BeginOfHour](#BeginOfHour)
- [BeginOfDay](#BeginOfDay)
- [BeginOfWeek](#BeginOfWeek)
- [BeginOfMonth](#BeginOfMonth)
- [BeginOfYear](#BeginOfYear)
- [EndOfMinute](#EndOfMinute)
- [EndOfHour](#EndOfHour)
- [EndOfDay](#EndOfDay)
- [EndOfWeek](#EndOfWeek)
- [EndOfMonth](#EndOfMonth)
- [EndOfYear](#EndOfYear)
- [GetNowDate](#GetNowDate)
- [GetNowTime](#GetNowTime)
- [GetNowDateTime](#GetNowDateTime)
- [GetZeroHourTimestamp](#GetZeroHourTimestamp)
- [GetNightTimestamp](#GetNightTimestamp)
- [FormatTimeToStr](#FormatTimeToStr)
- [FormatStrToTime](#FormatStrToTime)
- [NewUnixNow](#NewUnixNow)
- [NewUnix](#NewUnix)
- [NewFormat](#NewFormat)
- [NewISO8601](#NewISO8601)
- [ToUnix](#ToUnix)
- [ToFormat](#ToFormat)
- [ToFormatForTpl](#ToFormatForTpl)
- [ToIso8601](#ToIso8601)
- [IsLeapYear](#IsLeapYear)
<div STYLE="page-break-after: always;"></div>
## 文档
## 注:
1. 方法FormatTimeToStr和FormatStrToTime中的format参数值需要传以下类型之一
- yyyy-mm-dd hh:mm:ss
- yyyy-mm-dd hh:mm
- yyyy-mm-dd hh
- yyyy-mm-dd
- yyyy-mm
- mm-dd
- dd-mm-yy hh:mm:ss
- yyyy/mm/dd hh:mm:ss
- yyyy/mm/dd hh:mm
- yyyy-mm-dd hh
- yyyy/mm/dd
- yyyy/mm
- mm/dd
- dd/mm/yy hh:mm:ss
- yyyy
- mm
- hh:mm:ss
- mm:ss
1. 方法 FormatTimeToStr 和 FormatStrToTime 中的 format 参数值需要传以下类型之一:
- yyyy-mm-dd hh:mm:ss
- yyyy-mm-dd hh:mm
- yyyy-mm-dd hh
- yyyy-mm-dd
- yyyy-mm
- mm-dd
- dd-mm-yy hh:mm:ss
- yyyy/mm/dd hh:mm:ss
- yyyy/mm/dd hh:mm
- yyyy-mm-dd hh
- yyyy/mm/dd
- yyyy/mm
- mm/dd
- dd/mm/yy hh:mm:ss
- yyyy
- mm
- hh:mm:ss
- mm:ss
### <span id="AddDay">AddDay</span>
<p>将日期加/减天数。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func AddDay(t time.Time, day int64) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -119,13 +125,13 @@ func main() {
<p>将日期加/减小时数。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func AddHour(t time.Time, hour int64) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -158,13 +164,13 @@ func main() {
<p>将日期加/减分钟数。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func AddMinute(t time.Time, minute int64) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -193,17 +199,56 @@ func main() {
}
```
### <span id="AddYear">AddYear</span>
<p>将日期加/减年数。</p>
<b>函数签名:</b>
```go
func AddYear(t time.Time, year int64) time.Time
```
<b>示例:</b>
```go
package main
import (
"fmt"
"time"
"github.com/duke-git/lancet/v2/datetime"
)
func main() {
now := time.Now()
after1Year := AddYear(now, 1)
diff1 := after1Year.Sub(now)
before1Year := AddYear(now, -1)
diff2 := before1Year.Sub(now)
fmt.Println(diff1)
fmt.Println(diff2)
// Output:
// 8760h0m0s
// -8760h0m0s
}
```
### <span id="BeginOfMinute">BeginOfMinute</span>
<p>返回指定时间的分钟开始时间。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func BeginOfMinute(t time.Time) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -229,13 +274,13 @@ func main() {
<p>返回指定时间的小时开始时间。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func BeginOfHour(t time.Time) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -261,13 +306,13 @@ func main() {
<p>返回指定时间的当天开始时间。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func BeginOfDay(t time.Time) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -293,13 +338,13 @@ func main() {
<p>返回指定时间的每周开始时间,默认开始时间星期日。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func BeginOfWeek(t time.Time, beginFrom ...time.Weekday) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -325,13 +370,13 @@ func main() {
<p>返回指定时间的当月开始时间。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func BeginOfMonth(t time.Time) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -357,13 +402,13 @@ func main() {
<p>返回指定时间的当年开始时间</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func BeginOfYear(t time.Time) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -389,13 +434,13 @@ func main() {
<p>返回指定时间的分钟结束时间。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func EndOfMinute(t time.Time) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -421,13 +466,13 @@ func main() {
<p>返回指定时间的小时结束时间。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func EndOfHour(t time.Time) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -453,13 +498,13 @@ func main() {
<p>返回指定时间的当天结束时间。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func EndOfDay(t time.Time) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -485,13 +530,13 @@ func main() {
<p>返回指定时间的星期结束时间,默认结束时间星期六。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func EndOfWeek(t time.Time, endWith ...time.Weekday) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -517,13 +562,13 @@ func main() {
<p>返回指定时间的当月结束时间。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func EndOfMonth(t time.Time) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -549,13 +594,13 @@ func main() {
<p>返回指定时间的当年结束时间。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func EndOfYear(t time.Time) time.Time
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -581,13 +626,13 @@ func main() {
<p>获取当天日期返回格式yyyy-mm-dd。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func GetNowDate() string
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -602,8 +647,8 @@ func main() {
now := time.Now()
currentDate := datetime.GetNowDate()
fmt.Println(currentDate)
fmt.Println(currentDate)
// Output:
// 2022-01-28
}
@@ -613,13 +658,13 @@ func main() {
<p>获取当时时间返回格式hh:mm:ss</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func GetNowTime() string
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -645,13 +690,13 @@ func main() {
<p>获取当时日期和时间返回格式yyyy-mm-dd hh:mm:ss。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func GetNowDateTime() string
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -666,8 +711,8 @@ func main() {
now := time.Now()
current := datetime.GetNowDateTime()
fmt.Println(current)
fmt.Println(current)
// Output:
// 2022-01-28 15:59:33
}
@@ -677,13 +722,13 @@ func main() {
<p>获取零点时间戳(timestamp of 00:00)</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func GetZeroHourTimestamp() int64
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -697,9 +742,9 @@ import (
func main() {
now := time.Now()
zeroTime := datetime.GetZeroHourTimestamp()
fmt.Println(zeroTime)
fmt.Println(zeroTime)
// Output:
// 1643299200
}
@@ -709,13 +754,13 @@ func main() {
<p>获取午夜时间戳(timestamp of 23:59)。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func GetNightTimestamp() int64
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -730,8 +775,8 @@ func main() {
now := time.Now()
nightTime := datetime.GetNightTimestamp()
fmt.Println(nightTime)
fmt.Println(nightTime)
// Output:
// 1643385599
}
@@ -741,13 +786,13 @@ func main() {
<p>将日期格式化成字符串,`format` 参数格式参考注1。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func FormatTimeToStr(t time.Time, format string) string
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -780,13 +825,13 @@ func main() {
<p>将字符串格式化成时间,`format` 参数格式参考注1。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func FormatStrToTime(str, format string) (time.Time, error)
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -816,7 +861,7 @@ func main() {
<p>创建一个当前时间的unix时间戳。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
type theTime struct {
@@ -825,7 +870,7 @@ type theTime struct {
func NewUnixNow() *theTime
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -837,8 +882,8 @@ import (
func main() {
tm := datetime.NewUnixNow()
fmt.Println(tm)
fmt.Println(tm)
// Output:
// &{1647597438}
}
@@ -848,7 +893,7 @@ func main() {
<p>创建一个unix时间戳。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
type theTime struct {
@@ -857,7 +902,7 @@ type theTime struct {
func NewUnix(unix int64) *theTime
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -869,8 +914,8 @@ import (
func main() {
tm := datetime.NewUnix(1647597438)
fmt.Println(tm)
fmt.Println(tm)
// Output:
// &{1647597438}
}
@@ -880,7 +925,7 @@ func main() {
<p>创建一个yyyy-mm-dd hh:mm:ss格式时间字符串的unix时间戳。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
type theTime struct {
@@ -889,7 +934,7 @@ type theTime struct {
func NewFormat(t string) (*theTime, error)
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -901,8 +946,8 @@ import (
func main() {
tm, err := datetime.NewFormat("2022-03-18 17:04:05")
fmt.Println(tm)
fmt.Println(tm)
// Output:
// &{1647594245}
}
@@ -912,7 +957,7 @@ func main() {
<p>创建一个iso8601格式时间字符串的unix时间戳。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
type theTime struct {
@@ -921,7 +966,7 @@ type theTime struct {
func NewISO8601(iso8601 string) (*theTime, error)
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -933,8 +978,8 @@ import (
func main() {
tm, err := datetime.NewISO8601("2006-01-02T15:04:05.999Z")
fmt.Println(tm)
fmt.Println(tm)
// Output:
// &{1136214245}
}
@@ -944,13 +989,13 @@ func main() {
<p>返回unix时间戳。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func (t *theTime) ToUnix() int64
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -962,8 +1007,8 @@ import (
func main() {
tm := datetime.NewUnixNow()
fmt.Println(tm.ToUnix())
fmt.Println(tm.ToUnix())
// Output:
// 1647597438
}
@@ -973,13 +1018,13 @@ func main() {
<p>返回格式'yyyy-mm-dd hh:mm:ss'的日期字符串。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func (t *theTime) ToFormat() string
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -991,8 +1036,8 @@ import (
func main() {
tm, _ := datetime.NewFormat("2022-03-18 17:04:05")
fmt.Println(tm.ToFormat())
fmt.Println(tm.ToFormat())
// Output:
// 2022-03-18 17:04:05
}
@@ -1002,13 +1047,13 @@ func main() {
<p>返回tpl格式指定的日期字符串。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func (t *theTime) ToFormatForTpl(tpl string) string
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -1021,8 +1066,8 @@ import (
func main() {
tm, _ := datetime.NewFormat("2022-03-18 17:04:05")
ts := tm.ToFormatForTpl("2006/01/02 15:04:05")
fmt.Println(ts)
fmt.Println(ts)
// Output:
// 2022/03/18 17:04:05
}
@@ -1032,13 +1077,13 @@ func main() {
<p>返回iso8601日期字符串。</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func (t *theTime) ToIso8601() string
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -1051,9 +1096,43 @@ import (
func main() {
tm, _ := datetime.NewISO8601("2006-01-02T15:04:05.999Z")
ts := tm.ToIso8601()
fmt.Println(ts)
fmt.Println(ts)
// Output:
// 2006-01-02T23:04:05+08:00
}
```
```
### <span id="IsLeapYear">IsLeapYear</span>
<p>验证是否是闰年。</p>
<b>函数签名:</b>
```go
func IsLeapYear(year int) bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/datetime"
)
func main() {
result1 := datetime.IsLeapYear(2000)
result2 := datetime.IsLeapYear(2001)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```

View File

@@ -26,6 +26,7 @@ import (
- [CreateFile](#CreateFile)
- [CreateDir](#CreateDir)
- [CopyFile](#CopyFile)
- [CurrentPath](#CurrentPath)
- [FileMode](#FileMode)
- [MiMeType](#MiMeType)
- [IsExist](#IsExist)
@@ -37,7 +38,11 @@ import (
- [ReadFileByLine](#ReadFileByLine)
- [Zip](#Zip)
- [UnZip](#UnZip)
- [UnZip](#UnZip)
- [IsZipFile](#IsZipFile)
- [FileSize](#FileSize)
- [MTime](#MTime)
- [Sha](#Sha)
- [ReadCsvFile](#ReadCsvFile)
<div STYLE="page-break-after: always;"></div>
@@ -130,7 +135,7 @@ func main() {
<b>Signature:</b>
```go
func CopyFile(srcFilePath string, dstFilePath string) error
func CopyFile(srcPath string, dstPath string) error
```
<b>Example:</b>
@@ -151,6 +156,32 @@ func main() {
}
```
### <span id="CurrentPath">CurrentPath</span>
<p>return current absolute path.</p>
<b>Signature:</b>
```go
func CurrentPath() string
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
absPath := CurrentPath()
fmt.Println(absPath)
}
```
### <span id="FileMode">FileMode</span>
<p>Return file mode infomation.</p>
@@ -469,3 +500,163 @@ func main() {
}
}
```
### <span id="IsZipFile">IsZipFile</span>
<p>Checks if file is zip file or not.</p>
<b>Signature:</b>
```go
func IsZipFile(filepath string) bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
isZip := fileutil.IsZipFile("./zipfile.zip")
fmt.Println(isZip)
}
```
### <span id="FileSize">FileSize</span>
<p>Returns file size in bytes.</p>
<b>Signature:</b>
```go
func FileSize(path string) (int64, error)
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
size, err := fileutil.FileSize("./testdata/test.txt")
fmt.Println(size)
fmt.Println(err)
// Output:
// 20
// <nil>
}
```
### <span id="MTime">MTime</span>
<p>Returns file modified time(unix timestamp).</p>
<b>Signature:</b>
```go
func MTime(filepath string) (int64, error)
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
mtime, err := fileutil.MTime("./testdata/test.txt")
fmt.Println(mtime)
fmt.Println(err)
// Output:
// 1682391110
// <nil>
}
```
### <span id="Sha">Sha</span>
<p>returns file sha value, param `shaType` should be 1, 256 or 512.</p>
<b>Signature:</b>
```go
func Sha(filepath string, shaType ...int) (string, error)
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
sha1, err := fileutil.Sha("./testdata/test.txt", 1)
sha256, _ := fileutil.Sha("./testdata/test.txt", 256)
sha512, _ := fileutil.Sha("./testdata/test.txt", 512)
fmt.Println(sha1)
fmt.Println(sha256)
fmt.Println(sha512)
fmt.Println(err)
// Output:
// dda3cf10c5a6ff6c6659a497bf7261b287af2bc7
// aa6d0a3fbc3442c228d606da09e0c1dc98c69a1cac3da1909199e0266171df35
// d22aba2a1b7a2e2f512756255cc1c3708905646920cb1eb95e45b531ba74774dbbb89baebf1f716220eb9cf4908f1cfc5b2a01267704d9a59f59d77cab609870
// <nil>
}
```
### <span id="ReadCsvFile">ReadCsvFile</span>
<p>Reads file content into slice.</p>
<b>Signature:</b>
```go
func ReadCsvFile(filepath string) ([][]string, error)
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
content, err := fileutil.ReadCsvFile("./testdata/test.csv")
fmt.Println(content)
fmt.Println(err)
// Output:
// [[Bob 12 male] [Duke 14 male] [Lucy 16 female]]
// <nil>
}
```

View File

@@ -26,6 +26,7 @@ import (
- [CreateFile](#CreateFile)
- [CreateDir](#CreateDir)
- [CopyFile](#CopyFile)
- [CurrentPath](#CurrentPath)
- [FileMode](#FileMode)
- [MiMeType](#MiMeType)
- [IsExist](#IsExist)
@@ -37,6 +38,11 @@ import (
- [ReadFileByLine](#ReadFileByLine)
- [Zip](#Zip)
- [UnZip](#UnZip)
- [IsZipFile](#IsZipFile)
- [FileSize](#FileSize)
- [MTime](#MTime)
- [Sha](#Sha)
- [ReadCsvFile](#ReadCsvFile)
<div STYLE="page-break-after: always;"></div>
@@ -106,7 +112,7 @@ func main() {
func CreateDir(absPath string) error
```
<b>Example:</b>
<b>示例:</b>
```go
package main
@@ -129,7 +135,7 @@ func main() {
<b>函数签名:</b>
```go
func CopyFile(srcFilePath string, dstFilePath string) error
func CopyFile(srcPath string, dstPath string) error
```
<b>示例:</b>
@@ -150,6 +156,32 @@ func main() {
}
```
### <span id="CurrentPath">CurrentPath</span>
<p>返回当前位置的绝对路径。</p>
<b>函数签名:</b>
```go
func CurrentPath() string
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
absPath := CurrentPath()
fmt.Println(absPath)
}
```
### <span id="FileMode">FileMode</span>
<p>获取文件mode信息</p>
@@ -445,7 +477,7 @@ func main() {
<p>zip解压缩文件并保存在目录中</p>
<b>Signature:</b>
<b>函数签名:</b>
```go
func UnZip(zipFile string, destPath string) error
@@ -468,3 +500,163 @@ func main() {
}
}
```
### <span id="IsZipFile">IsZipFile</span>
<p>判断文件是否是zip压缩文件。</p>
<b>函数签名:</b>
```go
func IsZipFile(filepath string) bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
isZip := fileutil.IsZipFile("./zipfile.zip")
fmt.Println(isZip)
}
```
### <span id="FileSize">FileSize</span>
<p>返回文件字节大小。</p>
<b>函数签名:</b>
```go
func FileSize(path string) (int64, error)
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
size, err := fileutil.FileSize("./testdata/test.txt")
fmt.Println(size)
fmt.Println(err)
// Output:
// 20
// <nil>
}
```
### <span id="MTime">MTime</span>
<p>返回文件修改时间(unix timestamp).</p>
<b>函数签名:</b>
```go
func MTime(filepath string) (int64, error)
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
mtime, err := fileutil.MTime("./testdata/test.txt")
fmt.Println(mtime)
fmt.Println(err)
// Output:
// 1682391110
// <nil>
}
```
### <span id="Sha">Sha</span>
<p>返回文件sha值参数`shaType` 应传值为: 1, 256512.</p>
<b>函数签名:</b>
```go
func Sha(filepath string, shaType ...int) (string, error)
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
sha1, err := fileutil.Sha("./testdata/test.txt", 1)
sha256, _ := fileutil.Sha("./testdata/test.txt", 256)
sha512, _ := fileutil.Sha("./testdata/test.txt", 512)
fmt.Println(sha1)
fmt.Println(sha256)
fmt.Println(sha512)
fmt.Println(err)
// Output:
// dda3cf10c5a6ff6c6659a497bf7261b287af2bc7
// aa6d0a3fbc3442c228d606da09e0c1dc98c69a1cac3da1909199e0266171df35
// d22aba2a1b7a2e2f512756255cc1c3708905646920cb1eb95e45b531ba74774dbbb89baebf1f716220eb9cf4908f1cfc5b2a01267704d9a59f59d77cab609870
// <nil>
}
```
### <span id="ReadCsvFile">ReadCsvFile</span>
<p>读取csv文件内容到切片</p>
<b>函数签名:</b>
```go
func ReadCsvFile(filepath string) ([][]string, error)
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
content, err := fileutil.ReadCsvFile("./testdata/test.csv")
fmt.Println(content)
fmt.Println(err)
// Output:
// [[Bob 12 male] [Duke 14 male] [Lucy 16 female]]
// <nil>
}
```

View File

@@ -7,6 +7,7 @@ formatter contains some functions for data formatting.
## Source:
- [https://github.com/duke-git/lancet/blob/main/formatter/formatter.go](https://github.com/duke-git/lancet/blob/main/formatter/formatter.go)
- [https://github.com/duke-git/lancet/blob/main/formatter/byte.go](https://github.com/duke-git/lancet/blob/main/formatter/byte.go)
<div STYLE="page-break-after: always;"></div>
@@ -23,6 +24,12 @@ import (
## Index
- [Comma](#Comma)
- [Pretty](#Pretty)
- [PrettyToWriter](#PrettyToWriter)
- [DecimalBytes](#DecimalBytes)
- [BinaryBytes](#BinaryBytes)
- [ParseDecimalBytes](#ParseDecimalBytes)
- [ParseBinaryBytes](#ParseBinaryBytes)
<div STYLE="page-break-after: always;"></div>
@@ -63,3 +70,241 @@ func main() {
// ¥1,234,567
}
```
### <span id="Pretty">Pretty</span>
<p>Pretty data to JSON string.</p>
<b>Signature:</b>
```go
func Pretty(v any) (string, error)
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
result1, _ := formatter.Pretty([]string{"a", "b", "c"})
result2, _ := formatter.Pretty(map[string]int{"a": 1})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// [
// "a",
// "b",
// "c"
// ]
// {
// "a": 1
// }
}
```
### <span id="PrettyToWriter">PrettyToWriter</span>
<p>Pretty encode data to writer.</p>
<b>Signature:</b>
```go
func PrettyToWriter(v any, out io.Writer) error
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
type User struct {
Name string `json:"name"`
Aage uint `json:"age"`
}
user := User{Name: "King", Aage: 10000}
buf := &bytes.Buffer{}
err := formatter.PrettyToWriter(user, buf)
fmt.Println(buf)
fmt.Println(err)
// Output:
// {
// "name": "King",
// "age": 10000
// }
//
// <nil>
}
```
### <span id="DecimalBytes">DecimalBytes</span>
<p>Returns a human readable byte size under decimal standard (base 1000). The precision parameter specifies the number of digits after the decimal point, which is 4 for default.</p>
<b>Signature:</b>
```go
func DecimalBytes(size float64, precision ...int) string
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
result1 := formatter.DecimalBytes(1000)
result2 := formatter.DecimalBytes(1024)
result3 := formatter.DecimalBytes(1234567)
result4 := formatter.DecimalBytes(1234567, 3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 1KB
// 1.024KB
// 1.2346MB
// 1.235MB
}
```
### <span id="BinaryBytes">BinaryBytes</span>
<p>Returns a human readable byte size under binary standard (base 1024). The precision parameter specifies the number of digits after the decimal point, which is 4 for default.</p>
<b>Signature:</b>
```go
func BinaryBytes(size float64, precision ...int) string
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
result1 := formatter.BinaryBytes(1024)
result2 := formatter.BinaryBytes(1024 * 1024)
result3 := formatter.BinaryBytes(1234567)
result4 := formatter.BinaryBytes(1234567, 2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 1KiB
// 1MiB
// 1.1774MiB
// 1.18MiB
}
```
### <span id="ParseDecimalBytes">ParseDecimalBytes</span>
<p>Returns the human readable bytes size string into the amount it represents(base 1000).</p>
<b>Signature:</b>
```go
func ParseDecimalBytes(size string) (uint64, error)
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
result1, _ := formatter.ParseDecimalBytes("12")
result2, _ := formatter.ParseDecimalBytes("12k")
result3, _ := formatter.ParseDecimalBytes("12 Kb")
result4, _ := formatter.ParseDecimalBytes("12.2 kb")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 12
// 12000
// 12000
// 12200
}
```
### <span id="ParseBinaryBytes">ParseBinaryBytes</span>
<p>Returns the human readable bytes size string into the amount it represents(base 1024).</p>
<b>Signature:</b>
```go
func ParseBinaryBytes(size string) (uint64, error)
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
result1, _ := formatter.ParseBinaryBytes("12")
result2, _ := formatter.ParseBinaryBytes("12ki")
result3, _ := formatter.ParseBinaryBytes("12 KiB")
result4, _ := formatter.ParseBinaryBytes("12.2 kib")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 12
// 12288
// 12288
// 12492
}
```

View File

@@ -7,6 +7,7 @@ formatter 格式化器包含一些数据格式化处理方法。
## 源码:
- [https://github.com/duke-git/lancet/blob/main/formatter/formatter.go](https://github.com/duke-git/lancet/blob/main/formatter/formatter.go)
- [https://github.com/duke-git/lancet/blob/main/formatter/byte.go](https://github.com/duke-git/lancet/blob/main/formatter/byte.go)
<div STYLE="page-break-after: always;"></div>
@@ -23,6 +24,12 @@ import (
## 目录
- [Comma](#Comma)
- [Pretty](#Pretty)
- [PrettyToWriter](#PrettyToWriter)
- [DecimalBytes](#DecimalBytes)
- [BinaryBytes](#BinaryBytes)
- [ParseDecimalBytes](#ParseDecimalBytes)
- [ParseBinaryBytes](#ParseBinaryBytes)
<div STYLE="page-break-after: always;"></div>
@@ -63,3 +70,241 @@ func main() {
// ¥1,234,567
}
```
### <span id="Pretty">Pretty</span>
<p>返回pretty JSON字符串.</p>
<b>函数签名:</b>
```go
func Pretty(v any) (string, error)
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
result1, _ := formatter.Pretty([]string{"a", "b", "c"})
result2, _ := formatter.Pretty(map[string]int{"a": 1})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// [
// "a",
// "b",
// "c"
// ]
// {
// "a": 1
// }
}
```
### <span id="PrettyToWriter">PrettyToWriter</span>
<p>Pretty encode数据到writer。</p>
<b>函数签名:</b>
```go
func PrettyToWriter(v any, out io.Writer) error
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
type User struct {
Name string `json:"name"`
Aage uint `json:"age"`
}
user := User{Name: "King", Aage: 10000}
buf := &bytes.Buffer{}
err := formatter.PrettyToWriter(user, buf)
fmt.Println(buf)
fmt.Println(err)
// Output:
// {
// "name": "King",
// "age": 10000
// }
//
// <nil>
}
```
### <span id="DecimalBytes">DecimalBytes</span>
<p>返回十进制标准以1000为基数下的可读字节单位字符串。precision参数指定小数点后的位数默认为4。</p>
<b>函数签名:</b>
```go
func DecimalBytes(size float64, precision ...int) string
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
result1 := formatter.DecimalBytes(1000)
result2 := formatter.DecimalBytes(1024)
result3 := formatter.DecimalBytes(1234567)
result4 := formatter.DecimalBytes(1234567, 3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 1KB
// 1.024KB
// 1.2346MB
// 1.235MB
}
```
### <span id="BinaryBytes">BinaryBytes</span>
<p>返回binary标准以1024为基数下的可读字节单位字符串。precision参数指定小数点后的位数默认为4。</p>
<b>函数签名:</b>
```go
func BinaryBytes(size float64, precision ...int) string
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
result1 := formatter.BinaryBytes(1024)
result2 := formatter.BinaryBytes(1024 * 1024)
result3 := formatter.BinaryBytes(1234567)
result4 := formatter.BinaryBytes(1234567, 2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 1KiB
// 1MiB
// 1.1774MiB
// 1.18MiB
}
```
### <span id="ParseDecimalBytes">ParseDecimalBytes</span>
<p>将字节单位字符串转换成其所表示的字节数以1000为基数。</p>
<b>函数签名:</b>
```go
func ParseDecimalBytes(size string) (uint64, error)
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
result1, _ := formatter.ParseDecimalBytes("12")
result2, _ := formatter.ParseDecimalBytes("12k")
result3, _ := formatter.ParseDecimalBytes("12 Kb")
result4, _ := formatter.ParseDecimalBytes("12.2 kb")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 12
// 12000
// 12000
// 12200
}
```
### <span id="ParseBinaryBytes">ParseBinaryBytes</span>
<p>将字节单位字符串转换成其所表示的字节数以1024为基数。</p>
<b>函数签名:</b>
```go
func ParseBinaryBytes(size string) (uint64, error)
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/formatter"
)
func main() {
result1, _ := formatter.ParseBinaryBytes("12")
result2, _ := formatter.ParseBinaryBytes("12ki")
result3, _ := formatter.ParseBinaryBytes("12 KiB")
result4, _ := formatter.ParseBinaryBytes("12.2 kib")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 12
// 12288
// 12288
// 12492
}
```

View File

@@ -22,6 +22,7 @@ import (
## Index
- [MapTo](#MapTo)
- [ForEach](#ForEach)
- [Filter](#Filter)
- [FilterByKeys](#FilterByKeys)
@@ -47,6 +48,64 @@ import (
## Documentation
### <span id="MapTo">MapTo</span>
<p>Rry to map any interface to struct or base type.</p>
<b>Signature:</b>
```go
func MapTo(src any, dst any) error
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/maputil"
)
func main() {
type (
Person struct {
Name string `json:"name"`
Age int `json:"age"`
Phone string `json:"phone"`
Addr Address `json:"address"`
}
Address struct {
Street string `json:"street"`
Number int `json:"number"`
}
)
personInfo := map[string]interface{}{
"name": "Nothin",
"age": 28,
"phone": "123456789",
"address": map[string]interface{}{
"street": "test",
"number": 1,
},
}
var p Person
err := MapTo(personInfo, &p)
fmt.Println(err)
fmt.Println(p)
// Output:
// <nil>
// {Nothin 28 123456789 {test 1}}
}
```
### <span id="ForEach">ForEach</span>
<p>Executes iteratee funcation for every key and value pair in map.</p>
@@ -123,7 +182,7 @@ func main() {
maputil.Filter(m, func(_ string, value int) {
sum += value
})
result := maputil.Filter(m, isEven)
fmt.Println(result)
@@ -133,7 +192,6 @@ func main() {
}
```
### <span id="FilterByKeys">FilterByKeys</span>
<p>Iterates over map, return a new map whose keys are all given keys.</p>
@@ -172,7 +230,6 @@ func main() {
}
```
### <span id="FilterByValues">FilterByValues</span>
<p>Iterates over map, return a new map whose values are all given values.</p>
@@ -211,7 +268,6 @@ func main() {
}
```
### <span id="OmitBy">OmitBy</span>
<p>OmitBy is the opposite of Filter, removes all the map elements for which the predicate function returns true.</p>
@@ -253,7 +309,6 @@ func main() {
}
```
### <span id="OmitByKeys">OmitByKeys</span>
<p>The opposite of FilterByKeys, extracts all the map elements which keys are not omitted.</p>
@@ -292,7 +347,6 @@ func main() {
}
```
### <span id="OmitByValues">OmitByValues</span>
<p>The opposite of FilterByValues. remov all elements whose value are in the give slice.</p>
@@ -331,7 +385,6 @@ func main() {
}
```
### <span id="Intersect">Intersect</span>
<p>Iterates over maps, return a new map of key and value pairs in all given maps.</p>
@@ -419,7 +472,7 @@ func main() {
keys := maputil.Keys(m)
sort.Ints(keys)
fmt.Println(keys)
// Output:
@@ -498,7 +551,7 @@ func main() {
"b": 22,
"d": 33,
}
result := maputil.Minus(m1, m2)
fmt.Println(result)
@@ -638,7 +691,6 @@ func main() {
}
```
### <span id="MapKeys">MapKeys</span>
<p>Transforms a map to other type map by manipulating it's keys.</p>
@@ -717,7 +769,6 @@ func main() {
}
```
### <span id="Entry">Entry</span>
<p>Transforms a map into array of key/value pairs.</p>
@@ -763,7 +814,6 @@ func main() {
}
```
### <span id="FromEntries">FromEntries</span>
<p>Creates a map based on a slice of key/value pairs.</p>
@@ -841,7 +891,6 @@ func main() {
}
```
### <span id="IsDisjoint">IsDisjoint</span>
<p>Checks two maps are disjoint if they have no keys in common</p>

View File

@@ -22,6 +22,7 @@ import (
## 目录:
- [MapTo](#MapTo)
- [ForEach](#ForEach)
- [Filter](#Filter)
- [FilterByKeys](#FilterByKeys)
@@ -47,6 +48,63 @@ import (
## API 文档:
### <span id="MapTo">MapTo</span>
<p>快速将map或者其他类型映射到结构体或者指定类型。</p>
<b>函数签名:</b>
```go
func MapTo(src any, dst any) error
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/maputil"
)
func main() {
type (
Person struct {
Name string `json:"name"`
Age int `json:"age"`
Phone string `json:"phone"`
Addr Address `json:"address"`
}
Address struct {
Street string `json:"street"`
Number int `json:"number"`
}
)
personInfo := map[string]interface{}{
"name": "Nothin",
"age": 28,
"phone": "123456789",
"address": map[string]interface{}{
"street": "test",
"number": 1,
},
}
var p Person
err := MapTo(personInfo, &p)
fmt.Println(err)
fmt.Println(p)
// Output:
// <nil>
// {Nothin 28 123456789 {test 1}}
}
```
### <span id="ForEach">ForEach</span>
<p>对map中的每对key和value执行iteratee函数</p>
@@ -80,7 +138,7 @@ func main() {
maputil.ForEach(m, func(_ string, value int) {
sum += value
})
fmt.Println(sum)
// Output:
@@ -123,7 +181,7 @@ func main() {
maputil.Filter(m, func(_ string, value int) {
sum += value
})
result := Filter(m, isEven)
fmt.Println(result)
@@ -171,7 +229,6 @@ func main() {
}
```
### <span id="FilterByValues">FilterByValues</span>
<p>迭代map, 返回一个新map其value都是给定的value值。</p>
@@ -210,7 +267,6 @@ func main() {
}
```
### <span id="OmitBy">OmitBy</span>
<p>Filter的反向操作, 迭代map中的每对key和value, 删除符合predicate函数的key, value, 返回新map。</p>
@@ -252,7 +308,6 @@ func main() {
}
```
### <span id="OmitByKeys">OmitByKeys</span>
<p>FilterByKeys的反向操作, 迭代map, 返回一个新map其key不包括给定的key值。</p>
@@ -291,7 +346,6 @@ func main() {
}
```
### <span id="OmitByValues">OmitByValues</span>
<p>FilterByValues的反向操作, 迭代map, 返回一个新map其value不包括给定的value值。</p>
@@ -416,7 +470,7 @@ func main() {
keys := maputil.Keys(m)
sort.Ints(keys)
fmt.Println(keys)
// Output:
@@ -453,7 +507,7 @@ func main() {
1: "1",
3: "2",
}
result := maputil.Merge(m1, m2)
fmt.Println(result)
@@ -632,7 +686,6 @@ func main() {
}
```
### <span id="MapKeys">MapKeys</span>
<p>操作map的每个key然后转为新的map。</p>
@@ -711,7 +764,6 @@ func main() {
}
```
### <span id="Entry">Entry</span>
<p>将map转换为键/值对切片。</p>
@@ -757,7 +809,6 @@ func main() {
}
```
### <span id="FromEntries">FromEntries</span>
<p>基于键/值对的切片创建map。</p>

View File

@@ -34,6 +34,14 @@ import (
- [RoundToFloat](#RoundToFloat)
- [RoundToString](#RoundToString)
- [TruncRound](#TruncRound)
- [Range](#Range)
- [RangeWithStep](#RangeWithStep)
- [AngleToRadian](#AngleToRadian)
- [RadianToAngle](#RadianToAngle)
- [PointDistance](#PointDistance)
- [IsPrime](#IsPrime)
- [GCD](#GCD)
- [LCM](#LCM)
<div STYLE="page-break-after: always;"></div>
@@ -357,15 +365,18 @@ import (
)
func main() {
result1 := mathutil.Percent(1, 2, 2)
result2 := mathutil.Percent(0.1, 0.3, 2)
result1 := Percent(1, 2, 2)
result2 := Percent(0.1, 0.3, 2)
result3 := Percent(-30305, 408420, 2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.5
// 0.33
// Output:
// 50
// 33.33
// -7.42
}
```
@@ -476,3 +487,303 @@ func main() {
// 0.125
}
```
### <span id="Range">Range</span>
<p>Creates a slice of numbers from start with specified count, element step is 1.</p>
<b>Signature:</b>
```go
func Range[T constraints.Integer | constraints.Float](start T, count int) []T
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.Range(1, 4)
result2 := mathutil.Range(1, -4)
result3 := mathutil.Range(-4, 4)
result4 := mathutil.Range(1.0, 4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// [1 2 3 4]
// [1 2 3 4]
// [-4 -3 -2 -1]
// [1 2 3 4]
}
```
### <span id="RangeWithStep">RangeWithStep</span>
<p>Creates a slice of numbers from start to end with specified step.</p>
<b>Signature:</b>
```go
func RangeWithStep[T constraints.Integer | constraints.Float](start, end, step T) []T
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.RangeWithStep(1, 4, 1)
result2 := mathutil.RangeWithStep(1, -1, 0)
result3 := mathutil.RangeWithStep(-4, 1, 2)
result4 := mathutil.RangeWithStep(1.0, 4.0, 1.1)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// [1 2 3]
// []
// [-4 -2 0]
// [1 2.1 3.2]
}
```
### <span id="AngleToRadian">AngleToRadian</span>
<p>Converts angle value to radian value.</p>
<b>Signature:</b>
```go
func AngleToRadian(angle float64) float64
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.AngleToRadian(45)
result2 := mathutil.AngleToRadian(90)
result3 := mathutil.AngleToRadian(180)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.7853981633974483
// 1.5707963267948966
// 3.141592653589793
}
```
### <span id="RadianToAngle">RadianToAngle</span>
<p>Converts radian value to angle value.</p>
<b>Signature:</b>
```go
func RadianToAngle(radian float64) float64
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.RadianToAngle(math.Pi)
result2 := mathutil.RadianToAngle(math.Pi / 2)
result3 := mathutil.RadianToAngle(math.Pi / 4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 180
// 90
// 45
}
```
### <span id="PointDistance">PointDistance</span>
<p>Caculates two points distance.</p>
<b>Signature:</b>
```go
func PointDistance(x1, y1, x2, y2 float64) float64
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.PointDistance(1, 1, 4, 5)
fmt.Println(result1)
// Output:
// 5
}
```
### <span id="IsPrime">IsPrime</span>
<p>Checks if number is prime number.</p>
<b>Signature:</b>
```go
func IsPrime(n int) bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.IsPrime(-1)
result2 := mathutil.IsPrime(0)
result3 := mathutil.IsPrime(1)
result4 := mathutil.IsPrime(2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// false
// false
// false
// true
}
```
### <span id="GCD">GCD</span>
<p>Return greatest common divisor (GCD) of integers.</p>
<b>Signature:</b>
```go
func GCD[T constraints.Integer](integers ...T) T
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.GCD(1, 1)
result2 := mathutil.GCD(1, -1)
result3 := mathutil.GCD(-1, 1)
result4 := mathutil.GCD(-1, -1)
result5 := mathutil.GCD(3, 6, 9)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// 1
// 1
// -1
// -1
// 3
}
```
### <span id="LCM">LCM</span>
<p>Return Least Common Multiple (LCM) of integers.</p>
<b>Signature:</b>
```go
func LCM[T constraints.Integer](integers ...T) T
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.LCM(1, 1)
result2 := mathutil.LCM(1, 2)
result3 := mathutil.LCM(3, 6, 9)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 1
// 2
// 18
}
```

View File

@@ -34,6 +34,14 @@ import (
- [RoundToFloat](#RoundToFloat)
- [RoundToString](#RoundToString)
- [TruncRound](#TruncRound)
- [Range](#Range)
- [RangeWithStep](#RangeWithStep)
- [AngleToRadian](#AngleToRadian)
- [RadianToAngle](#RadianToAngle)
- [PointDistance](#PointDistance)
- [IsPrime](#IsPrime)
- [GCD](#GCD)
- [LCM](#LCM)
<div STYLE="page-break-after: always;"></div>
@@ -357,15 +365,18 @@ import (
)
func main() {
result1 := mathutil.Percent(1, 2, 2)
result2 := mathutil.Percent(0.1, 0.3, 2)
result1 := Percent(1, 2, 2)
result2 := Percent(0.1, 0.3, 2)
result3 := Percent(-30305, 408420, 2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.5
// 0.33
// Output:
// 50
// 33.33
// -7.42
}
```
@@ -476,3 +487,303 @@ func main() {
// 0.125
}
```
### <span id="Range">Range</span>
<p>根据指定的起始值和数量,创建一个数字切片。</p>
<b>函数签名:</b>
```go
func Range[T constraints.Integer | constraints.Float](start T, count int) []T
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.Range(1, 4)
result2 := mathutil.Range(1, -4)
result3 := mathutil.Range(-4, 4)
result4 := mathutil.Range(1.0, 4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// [1 2 3 4]
// [1 2 3 4]
// [-4 -3 -2 -1]
// [1 2 3 4]
}
```
### <span id="RangeWithStep">RangeWithStep</span>
<p>根据指定的起始值,结束值,步长,创建一个数字切片。</p>
<b>函数签名:</b>
```go
func RangeWithStep[T constraints.Integer | constraints.Float](start, end, step T) []T
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.RangeWithStep(1, 4, 1)
result2 := mathutil.RangeWithStep(1, -1, 0)
result3 := mathutil.RangeWithStep(-4, 1, 2)
result4 := mathutil.RangeWithStep(1.0, 4.0, 1.1)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// [1 2 3]
// []
// [-4 -2 0]
// [1 2.1 3.2]
}
```
### <span id="AngleToRadian">AngleToRadian</span>
<p>将角度值转为弧度值</p>
<b>函数签名:</b>
```go
func AngleToRadian(angle float64) float64
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.AngleToRadian(45)
result2 := mathutil.AngleToRadian(90)
result3 := mathutil.AngleToRadian(180)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.7853981633974483
// 1.5707963267948966
// 3.141592653589793
}
```
### <span id="RadianToAngle">RadianToAngle</span>
<p>将弧度值转为角度值</p>
<b>函数签名:</b>
```go
func RadianToAngle(radian float64) float64
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.RadianToAngle(math.Pi)
result2 := mathutil.RadianToAngle(math.Pi / 2)
result3 := mathutil.RadianToAngle(math.Pi / 4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 180
// 90
// 45
}
```
### <span id="PointDistance">PointDistance</span>
<p>计算两个坐标点的距离</p>
<b>函数签名:</b>
```go
func PointDistance(x1, y1, x2, y2 float64) float64
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.PointDistance(1, 1, 4, 5)
fmt.Println(result1)
// Output:
// 5
}
```
### <span id="IsPrime">IsPrime</span>
<p>判断质数。</p>
<b>函数签名:</b>
```go
func IsPrime(n int) bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.IsPrime(-1)
result2 := mathutil.IsPrime(0)
result3 := mathutil.IsPrime(1)
result4 := mathutil.IsPrime(2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// false
// false
// false
// true
}
```
### <span id="GCD">GCD</span>
<p>计算最大公约数。</p>
<b>函数签名:</b>
```go
func GCD[T constraints.Integer](integers ...T) T
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.GCD(1, 1)
result2 := mathutil.GCD(1, -1)
result3 := mathutil.GCD(-1, 1)
result4 := mathutil.GCD(-1, -1)
result5 := mathutil.GCD(3, 6, 9)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// 1
// 1
// -1
// -1
// 3
}
```
### <span id="LCM">LCM</span>
<p>计算最小公倍数。</p>
<b>函数签名:</b>
```go
func LCM[T constraints.Integer](integers ...T) T
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.LCM(1, 1)
result2 := mathutil.LCM(1, 2)
result3 := mathutil.LCM(3, 6, 9)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 1
// 2
// 18
}
```

View File

@@ -44,6 +44,10 @@ import (
- [HttpPut<sup>Deprecated</sup>](#HttpPut)
- [HttpPatch<sup>Deprecated</sup>](#HttpPatch)
- [ParseHttpResponse](#ParseHttpResponse)
- [DownloadFile](#DownloadFile)
- [UploadFile](#UploadFile)
- [IsPingConnected](#IsPingConnected)
- [IsTelnetConnected](#IsTelnetConnected)
<div STYLE="page-break-after: always;"></div>
@@ -110,8 +114,8 @@ func main() {
fmt.Println(err)
}
fmt.Println(encodedUrl)
fmt.Println(encodedUrl)
// Output:
// http://www.lancet.com?a=1&b=%5B2%5D
}
@@ -142,8 +146,8 @@ func main() {
internalIp := netutil.GetInternalIp()
ip := net.ParseIP(internalIp)
fmt.Println(ip)
fmt.Println(ip)
// Output:
// 192.168.1.9
}
@@ -172,7 +176,7 @@ import (
func main() {
ips := netutil.GetIps()
fmt.Println(ips)
fmt.Println(ips)
// Output:
// [192.168.1.9]
@@ -590,21 +594,29 @@ import (
func main() {
type TodoQuery struct {
Id int `json:"id"`
Name string `json:"name"`
Id int `json:"id"`
UserId int `json:"userId"`
Name string `json:"name,omitempty"`
Status string
}
todoQuery := TodoQuery{
Id: 1,
Name: "Test",
item := TodoQuery{
Id: 1,
UserId: 123,
Name: "test",
Status: "completed",
}
todoValues := netutil.StructToUrlValues(todoQuery)
queryValues := netutil.StructToUrlValues(item)
fmt.Println(todoValues.Get("id"))
fmt.Println(todoValues.Get("userId"))
fmt.Println(todoValues.Get("name"))
fmt.Println(todoValues.Get("status"))
// Output:
// 1
// Test
// 123
// test
//
}
```
@@ -888,3 +900,124 @@ func main() {
fmt.Println(toDoResp)
}
```
### <span id="DownloadFile">DownloadFile</span>
<p>Download the file exist in url to a local file.</p>
<b>Signature:</b>
```go
func DownloadFile(filepath string, url string) error
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/netutil"
)
func main() {
err := netutil.DownloadFile("./lancet_logo.jpg", "https://picx.zhimg.com/v2-fc82a4199749de9cfb71e32e54f489d3_720w.jpg?source=172ae18b")
fmt.Println(err)
}
```
### <span id="UploadFile">UploadFile</span>
<p>Upload the file to a server.</p>
<b>Signature:</b>
```go
func UploadFile(filepath string, server string) (bool, error)
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/netutil"
)
func main() {
ok, err := netutil.UploadFile("./a.jpg", "http://www.xxx.com/bucket/test")
fmt.Println(ok)
fmt.Println(err)
}
```
### <span id="IsPingConnected">IsPingConnected</span>
<p>checks if can ping the specified host or not.</p>
<b>Signature:</b>
```go
func IsPingConnected(host string) bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/netutil"
)
func main() {
result1 := netutil.IsPingConnected("www.baidu.com")
result2 := netutil.IsPingConnected("www.!@#&&&.com")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="IsTelnetConnected">IsTelnetConnected</span>
<p>Checks if can telnet the specified host or not.</p>
<b>Signature:</b>
```go
func IsTelnetConnected(host string, port string) bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/netutil"
)
func main() {
result1 := netutil.IsTelnetConnected("www.baidu.com", "80")
result2 := netutil.IsTelnetConnected("www.baidu.com", "123")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```

View File

@@ -44,6 +44,10 @@ import (
- [HttpPut<sup>Deprecated</sup>](#HttpPut)
- [HttpPatch<sup>Deprecated</sup>](#HttpPatch)
- [ParseHttpResponse](#ParseHttpResponse)
- [DownloadFile](#DownloadFile)
- [UploadFile](#UploadFile)
- [IsPingConnected](#IsPingConnected)
- [IsTelnetConnected](#IsTelnetConnected)
<div STYLE="page-break-after: always;"></div>
@@ -592,21 +596,29 @@ import (
func main() {
type TodoQuery struct {
Id int `json:"id"`
Name string `json:"name"`
Id int `json:"id"`
UserId int `json:"userId"`
Name string `json:"name,omitempty"`
Status string
}
todoQuery := TodoQuery{
Id: 1,
Name: "Test",
item := TodoQuery{
Id: 1,
UserId: 123,
Name: "test",
Status: "completed",
}
todoValues := netutil.StructToUrlValues(todoQuery)
queryValues := netutil.StructToUrlValues(item)
fmt.Println(todoValues.Get("id"))
fmt.Println(todoValues.Get("userId"))
fmt.Println(todoValues.Get("name"))
fmt.Println(todoValues.Get("status"))
// Output:
// 1
// Test
// 123
// test
//
}
```
@@ -890,3 +902,124 @@ func main() {
fmt.Println(toDoResp)
}
```
### <span id="DownloadFile">DownloadFile</span>
<p>从指定的server地址下载文件。</p>
<b>函数签名:</b>
```go
func DownloadFile(filepath string, url string) error
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/netutil"
)
func main() {
err := netutil.DownloadFile("./lancet_logo.jpg", "https://picx.zhimg.com/v2-fc82a4199749de9cfb71e32e54f489d3_720w.jpg?source=172ae18b")
fmt.Println(err)
}
```
### <span id="UploadFile">UploadFile</span>
<p>将文件上传指定的server地址。</p>
<b>函数签名:</b>
```go
func UploadFile(filepath string, server string) (bool, error)
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/netutil"
)
func main() {
ok, err := netutil.UploadFile("./a.jpg", "http://www.xxx.com/bucket/test")
fmt.Println(ok)
fmt.Println(err)
}
```
### <span id="IsPingConnected">IsPingConnected</span>
<p>检查能否ping通主机。</p>
<b>函数签名:</b>
```go
func IsPingConnected(host string) bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/netutil"
)
func main() {
result1 := netutil.IsPingConnected("www.baidu.com")
result2 := netutil.IsPingConnected("www.!@#&&&.com")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="IsTelnetConnected">IsTelnetConnected</span>
<p>检查能否telnet到主机。</p>
<b>函数签名:</b>
```go
func IsTelnetConnected(host string, port string) bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/netutil"
)
func main() {
result1 := netutil.IsTelnetConnected("www.baidu.com", "80")
result2 := netutil.IsTelnetConnected("www.baidu.com", "123")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```

View File

@@ -43,11 +43,14 @@ import (
- [EqualWith](#EqualWith)
- [Every](#Every)
- [Filter](#Filter)
- [Find](#Find)
- [FindLast](#FindLast)
- [Find<sup>deprecated</sup>](#Find)
- [FindBy](#FindBy)
- [FindLast<sup>deprecated</sup>](#FindLast)
- [FindLastBy](#FindLastBy)
- [Flatten](#Flatten)
- [FlattenDeep](#FlattenDeep)
- [ForEach](#ForEach)
- [ForEachWithBreak](#ForEachWithBreak)
- [GroupBy](#GroupBy)
- [GroupWith](#GroupWith)
- [IntSlice<sup>deprecated</sup>](#IntSlice)
@@ -61,7 +64,9 @@ import (
- [FlatMap](#FlatMap)
- [Merge](#Merge)
- [Reverse](#Reverse)
- [Reduce](#Reduce)
- [Reduce<sup>deprecated</sup>](#Reduce)
- [ReduceBy](#ReduceBy)
- [ReduceRight](#ReduceRight)
- [Replace](#Replace)
- [ReplaceAll](#ReplaceAll)
- [Repeat](#Repeat)
@@ -172,28 +177,28 @@ import (
func main() {
type foo struct {
A string
B int
}
A string
B int
}
array1 := []foo{{A: "1", B: 1}, {A: "2", B: 2}}
result1 := slice.ContainBy(array1, func(f foo) bool { return f.A == "1" && f.B == 1 })
result2 := slice.ContainBy(array1, func(f foo) bool { return f.A == "2" && f.B == 1 })
array1 := []foo{{A: "1", B: 1}, {A: "2", B: 2}}
result1 := slice.ContainBy(array1, func(f foo) bool { return f.A == "1" && f.B == 1 })
result2 := slice.ContainBy(array1, func(f foo) bool { return f.A == "2" && f.B == 1 })
array2 := []string{"a", "b", "c"}
result3 := slice.ContainBy(array2, func(t string) bool { return t == "a" })
result4 := slice.ContainBy(array2, func(t string) bool { return t == "d" })
array2 := []string{"a", "b", "c"}
result3 := slice.ContainBy(array2, func(t string) bool { return t == "a" })
result4 := slice.ContainBy(array2, func(t string) bool { return t == "d" })
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// false
// true
// false
// Output:
// true
// false
// true
// false
}
```
@@ -560,20 +565,20 @@ import (
func main() {
result1 := slice.Drop([]string{"a", "b", "c"}, 0)
result2 := slice.Drop([]string{"a", "b", "c"}, 1)
result3 := slice.Drop([]string{"a", "b", "c"}, -1)
result4 := slice.Drop([]string{"a", "b", "c"}, 4)
result2 := slice.Drop([]string{"a", "b", "c"}, 1)
result3 := slice.Drop([]string{"a", "b", "c"}, -1)
result4 := slice.Drop([]string{"a", "b", "c"}, 4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// [a b c]
// [b c]
// [a b c]
// []
// Output:
// [a b c]
// [b c]
// [a b c]
// []
}
```
@@ -597,20 +602,20 @@ import (
func main() {
result1 := slice.DropRight([]string{"a", "b", "c"}, 0)
result2 := slice.DropRight([]string{"a", "b", "c"}, 1)
result3 := slice.DropRight([]string{"a", "b", "c"}, -1)
result4 := slice.DropRight([]string{"a", "b", "c"}, 4)
result2 := slice.DropRight([]string{"a", "b", "c"}, 1)
result3 := slice.DropRight([]string{"a", "b", "c"}, -1)
result4 := slice.DropRight([]string{"a", "b", "c"}, 4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// [a b c]
// [a b]
// [a b c]
// []
// Output:
// [a b c]
// [a b]
// [a b c]
// []
}
```
@@ -634,23 +639,23 @@ import (
func main() {
result1 := slice.DropWhile(numbers, func(n int) bool {
return n != 2
})
result2 := slice.DropWhile(numbers, func(n int) bool {
return true
})
result3 := slice.DropWhile(numbers, func(n int) bool {
return n == 0
})
return n != 2
})
result2 := slice.DropWhile(numbers, func(n int) bool {
return true
})
result3 := slice.DropWhile(numbers, func(n int) bool {
return n == 0
})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// [2 3 4 5]
// []
// [1 2 3 4 5]
// Output:
// [2 3 4 5]
// []
// [1 2 3 4 5]
}
```
@@ -675,24 +680,24 @@ import (
func main() {
numbers := []int{1, 2, 3, 4, 5}
result1 := slice.DropRightWhile(numbers, func(n int) bool {
return n != 2
})
result2 := slice.DropRightWhile(numbers, func(n int) bool {
return true
})
result3 := slice.DropRightWhile(numbers, func(n int) bool {
return n == 0
})
result1 := slice.DropRightWhile(numbers, func(n int) bool {
return n != 2
})
result2 := slice.DropRightWhile(numbers, func(n int) bool {
return true
})
result3 := slice.DropRightWhile(numbers, func(n int) bool {
return n == 0
})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// [1 2]
// []
// [1 2 3 4 5]
// Output:
// [1 2]
// []
// [1 2 3 4 5]
}
```
@@ -834,7 +839,7 @@ func main() {
}
```
### <span id="Find">Find</span>
### <span id="Find">Find(deprecated: use FindBy)</span>
<p>Iterates over elements of slice, returning the first one that passes a truth test on function.</p>
@@ -870,7 +875,43 @@ func main() {
}
```
### <span id="FindLast">FindLast</span>
### <span id="FindBy">FindBy</span>
<p>Iterates over elements of slice, returning the first one that passes a truth test on predicate function.If return T is nil or zero value then no items matched the predicate func. In contrast to Find or FindLast, its return value no longer requires dereferencing</p>
<b>Signature:</b>
```go
func FindBy[T any](slice []T, predicate func(index int, item T) bool) (v T, ok bool)
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
nums := []int{1, 2, 3, 4, 5}
isEven := func(i, num int) bool {
return num%2 == 0
}
result, ok := slice.FindBy(nums, isEven)
fmt.Println(result)
fmt.Println(ok)
// Output:
// 2
// true
}
```
### <span id="FindLast">FindLast(deprecated: use FindLastBy)</span>
<p>iterates over elements of slice from end to begin, returning the last one that passes a truth test on function.</p>
@@ -906,6 +947,42 @@ func main() {
}
```
### <span id="FindLastBy">FindLastBy</span>
<p>FindLastBy iterates over elements of slice, returning the last one that passes a truth test on predicate function. If return T is nil or zero value then no items matched the predicate func. In contrast to Find or FindLast, its return value no longer requires dereferencing</p>
<b>Signature:</b>
```go
func FindLastBy[T any](slice []T, predicate func(index int, item T) bool) (v T, ok bool)
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
nums := []int{1, 2, 3, 4, 5}
isEven := func(i, num int) bool {
return num%2 == 0
}
result, ok := slice.FindLastBy(nums, isEven)
fmt.Println(result)
fmt.Println(ok)
// Output:
// 4
// true
}
```
### <span id="Flatten">Flatten</span>
<p>Flatten slice with one level.</p>
@@ -1001,6 +1078,44 @@ func main() {
}
```
### <span id="ForEachWithBreak">ForEachWithBreak</span>
<p>Iterates over elements of slice and invokes function for each element, when iteratee return false, will break the for each loop.</p>
<b>Signature:</b>
```go
func ForEachWithBreak[T any](slice []T, iteratee func(index int, item T) bool)
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
numbers := []int{1, 2, 3, 4, 5}
var sum int
slice.ForEachWithBreak(numbers, func(_, n int) bool {
if n > 3 {
return false
}
sum += n
return true
})
fmt.Println(sum)
// Output:
// 6
}
```
### <span id="GroupBy">GroupBy</span>
<p>Iterates over elements of the slice, each element will be group by criteria, returns two slices.</p>
@@ -1321,19 +1436,19 @@ import (
func main() {
nums := []int{1, 2, 3, 4, 5}
getEvenNumStr := func(i, num int) (string, bool) {
if num%2 == 0 {
return strconv.FormatInt(int64(num), 10), true
}
return "", false
}
getEvenNumStr := func(i, num int) (string, bool) {
if num%2 == 0 {
return strconv.FormatInt(int64(num), 10), true
}
return "", false
}
result := slice.FilterMap(nums, getEvenNumStr)
result := slice.FilterMap(nums, getEvenNumStr)
fmt.Printf("%#v", result)
fmt.Printf("%#v", result)
// Output:
// []string{"2", "4"}
// Output:
// []string{"2", "4"}
}
```
@@ -1358,15 +1473,15 @@ import (
func main() {
nums := []int{1, 2, 3, 4}
result := slice.FlatMap(nums, func(i int, num int) []string {
s := "hi-" + strconv.FormatInt(int64(num), 10)
return []string{s}
})
result := slice.FlatMap(nums, func(i int, num int) []string {
s := "hi-" + strconv.FormatInt(int64(num), 10)
return []string{s}
})
fmt.Printf("%#v", result)
fmt.Printf("%#v", result)
// Output:
// []string{"hi-1", "hi-2", "hi-3", "hi-4"}
// Output:
// []string{"hi-1", "hi-2", "hi-3", "hi-4"}
}
```
@@ -1433,7 +1548,7 @@ func main() {
### <span id="Reduce">Reduce</span>
<p>Reduce slice.</p>
<p>Reduce slice.(Deprecated: use ReduceBy)</p>
<b>Signature:</b>
@@ -1465,6 +1580,72 @@ func main() {
}
```
### <span id="ReduceBy">ReduceBy</span>
<p>Produces a value from slice by accumulating the result of each element as passed through the reducer function.</p>
<b>Signature:</b>
```go
func ReduceBy[T any, U any](slice []T, initial U, reducer func(index int, item T, agg U) U) U
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
result1 := slice.ReduceBy([]int{1, 2, 3, 4}, 0, func(_ int, item int, agg int) int {
return agg + item
})
result2 := slice.ReduceBy([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 10
// 1234
}
```
### <span id="ReduceRight">ReduceRight</span>
<p>ReduceRight is like ReduceBy, but it iterates over elements of slice from right to left.</p>
<b>Signature:</b>
```go
func ReduceRight[T any, U any](slice []T, initial U, reducer func(index int, item T, agg U) U) U
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
result := slice.ReduceRight([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
fmt.Println(result)
// Output:
// 4321
}
```
### <span id="Replace">Replace</span>
<p>Returns a copy of the slice with the first n non-overlapping instances of old replaced by new.</p>
@@ -1612,17 +1793,17 @@ import (
func main() {
result1 := slice.IsAscending([]int{1, 2, 3, 4, 5})
result2 := slice.IsAscending([]int{5, 4, 3, 2, 1})
result3 := slice.IsAscending([]int{2, 1, 3, 4, 5})
result2 := slice.IsAscending([]int{5, 4, 3, 2, 1})
result3 := slice.IsAscending([]int{2, 1, 3, 4, 5})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// true
// false
// false
// Output:
// true
// false
// false
}
```
@@ -1646,17 +1827,17 @@ import (
func main() {
result1 := slice.IsDescending([]int{5, 4, 3, 2, 1})
result2 := slice.IsDescending([]int{1, 2, 3, 4, 5})
result3 := slice.IsDescending([]int{2, 1, 3, 4, 5})
result2 := slice.IsDescending([]int{1, 2, 3, 4, 5})
result3 := slice.IsDescending([]int{2, 1, 3, 4, 5})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// true
// false
// false
// Output:
// true
// false
// false
}
```
@@ -1680,17 +1861,17 @@ import (
func main() {
result1 := slice.IsSorted([]int{5, 4, 3, 2, 1})
result2 := slice.IsSorted([]int{1, 2, 3, 4, 5})
result3 := slice.IsSorted([]int{2, 1, 3, 4, 5})
result2 := slice.IsSorted([]int{1, 2, 3, 4, 5})
result3 := slice.IsSorted([]int{2, 1, 3, 4, 5})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// true
// true
// false
// Output:
// true
// true
// false
}
```
@@ -1714,23 +1895,23 @@ import (
func main() {
result1 := slice.IsSortedByKey([]string{"a", "ab", "abc"}, func(s string) int {
return len(s)
})
result2 := slice.IsSortedByKey([]string{"abc", "ab", "a"}, func(s string) int {
return len(s)
})
result3 := slice.IsSortedByKey([]string{"abc", "a", "ab"}, func(s string) int {
return len(s)
})
return len(s)
})
result2 := slice.IsSortedByKey([]string{"abc", "ab", "a"}, func(s string) int {
return len(s)
})
result3 := slice.IsSortedByKey([]string{"abc", "a", "ab"}, func(s string) int {
return len(s)
})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// true
// true
// false
// Output:
// true
// true
// false
}
```

View File

@@ -43,11 +43,14 @@ import (
- [Equal](#Equal)
- [EqualWith](#EqualWith)
- [Filter](#Filter)
- [Find](#Find)
- [FindLast](#FindLast)
- [Find<sup>deprecated</sup>](#Find)
- [FindBy](#FindBy)
- [FindLast<sup>deprecated</sup>](#FindLast)
- [FindLastBy](#FindLastBy)
- [Flatten](#Flatten)
- [FlattenDeep](#FlattenDeep)
- [ForEach](#ForEach)
- [ForEachWithBreak](#ForEachWithBreak)
- [GroupBy](#GroupBy)
- [GroupWith](#GroupWith)
- [IntSlice<sup>deprecated</sup>](#IntSlice)
@@ -61,7 +64,9 @@ import (
- [FlatMap](#FlatMap)
- [Merge](#Merge)
- [Reverse](#Reverse)
- [Reduce](#Reduce)
- [Reduce<sup>deprecated</sup>](#Reduce)
- [ReduceBy](#ReduceBy)
- [ReduceRight](#ReduceRight)
- [Replace](#Replace)
- [ReplaceAll](#ReplaceAll)
- [Repeat](#Repeat)
@@ -172,28 +177,28 @@ import (
func main() {
type foo struct {
A string
B int
}
A string
B int
}
array1 := []foo{{A: "1", B: 1}, {A: "2", B: 2}}
result1 := slice.ContainBy(array1, func(f foo) bool { return f.A == "1" && f.B == 1 })
result2 := slice.ContainBy(array1, func(f foo) bool { return f.A == "2" && f.B == 1 })
array1 := []foo{{A: "1", B: 1}, {A: "2", B: 2}}
result1 := slice.ContainBy(array1, func(f foo) bool { return f.A == "1" && f.B == 1 })
result2 := slice.ContainBy(array1, func(f foo) bool { return f.A == "2" && f.B == 1 })
array2 := []string{"a", "b", "c"}
result3 := slice.ContainBy(array2, func(t string) bool { return t == "a" })
result4 := slice.ContainBy(array2, func(t string) bool { return t == "d" })
array2 := []string{"a", "b", "c"}
result3 := slice.ContainBy(array2, func(t string) bool { return t == "a" })
result4 := slice.ContainBy(array2, func(t string) bool { return t == "d" })
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// false
// true
// false
// Output:
// true
// false
// true
// false
}
```
@@ -541,7 +546,6 @@ func main() {
}
```
### <span id="Drop">Drop</span>
<p>从切片的头部删除n个元素。</p>
@@ -562,20 +566,20 @@ import (
func main() {
result1 := slice.Drop([]string{"a", "b", "c"}, 0)
result2 := slice.Drop([]string{"a", "b", "c"}, 1)
result3 := slice.Drop([]string{"a", "b", "c"}, -1)
result4 := slice.Drop([]string{"a", "b", "c"}, 4)
result2 := slice.Drop([]string{"a", "b", "c"}, 1)
result3 := slice.Drop([]string{"a", "b", "c"}, -1)
result4 := slice.Drop([]string{"a", "b", "c"}, 4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// [a b c]
// [b c]
// [a b c]
// []
// Output:
// [a b c]
// [b c]
// [a b c]
// []
}
```
@@ -599,20 +603,20 @@ import (
func main() {
result1 := slice.DropRight([]string{"a", "b", "c"}, 0)
result2 := slice.DropRight([]string{"a", "b", "c"}, 1)
result3 := slice.DropRight([]string{"a", "b", "c"}, -1)
result4 := slice.DropRight([]string{"a", "b", "c"}, 4)
result2 := slice.DropRight([]string{"a", "b", "c"}, 1)
result3 := slice.DropRight([]string{"a", "b", "c"}, -1)
result4 := slice.DropRight([]string{"a", "b", "c"}, 4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// [a b c]
// [a b]
// [a b c]
// []
// Output:
// [a b c]
// [a b]
// [a b c]
// []
}
```
@@ -636,23 +640,23 @@ import (
func main() {
result1 := slice.DropWhile(numbers, func(n int) bool {
return n != 2
})
result2 := slice.DropWhile(numbers, func(n int) bool {
return true
})
result3 := slice.DropWhile(numbers, func(n int) bool {
return n == 0
})
return n != 2
})
result2 := slice.DropWhile(numbers, func(n int) bool {
return true
})
result3 := slice.DropWhile(numbers, func(n int) bool {
return n == 0
})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// [2 3 4 5]
// []
// [1 2 3 4 5]
// Output:
// [2 3 4 5]
// []
// [1 2 3 4 5]
}
```
@@ -677,24 +681,24 @@ import (
func main() {
numbers := []int{1, 2, 3, 4, 5}
result1 := slice.DropRightWhile(numbers, func(n int) bool {
return n != 2
})
result2 := slice.DropRightWhile(numbers, func(n int) bool {
return true
})
result3 := slice.DropRightWhile(numbers, func(n int) bool {
return n == 0
})
result1 := slice.DropRightWhile(numbers, func(n int) bool {
return n != 2
})
result2 := slice.DropRightWhile(numbers, func(n int) bool {
return true
})
result3 := slice.DropRightWhile(numbers, func(n int) bool {
return n == 0
})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// [1 2]
// []
// [1 2 3 4 5]
// Output:
// [1 2]
// []
// [1 2 3 4 5]
}
```
@@ -836,9 +840,9 @@ func main() {
}
```
### <span id="Find">Find</span>
### <span id="Find">Find (废弃:使用 FindBy)</span>
<p>遍历切片的元素返回第一个通过predicate函数真值测试的元素</p>
<p>遍历slice的元素返回第一个通过predicate函数真值测试的元素</p>
<b>函数签名:</b>
@@ -872,9 +876,45 @@ func main() {
}
```
### <span id="FindLast">FindLast</span>
### <span id="FindBy">FindBy</span>
<p>从头到尾遍历slice的元素返回最后一个通过predicate函数真值测试的元素</p>
<p>遍历slice的元素返回一个通过predicate函数真值测试的元素</p>
<b>函数签名:</b>
```go
func FindBy[T any](slice []T, predicate func(index int, item T) bool) (v T, ok bool)
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
nums := []int{1, 2, 3, 4, 5}
isEven := func(i, num int) bool {
return num%2 == 0
}
result, ok := slice.FindBy(nums, isEven)
fmt.Println(result)
fmt.Println(ok)
// Output:
// 2
// true
}
```
### <span id="FindLast">FindLast(废弃:使用 FindLastBy)</span>
<p>遍历slice的元素返回最后一个通过predicate函数真值测试的元素。</p>
<b>函数签名:</b>
@@ -908,6 +948,42 @@ func main() {
}
```
### <span id="FindLastBy">FindLastBy</span>
<p>从遍历slice的元素返回最后一个通过predicate函数真值测试的元素。</p>
<b>函数签名:</b>
```go
func FindLastBy[T any](slice []T, predicate func(index int, item T) bool) (v T, ok bool)
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
nums := []int{1, 2, 3, 4, 5}
isEven := func(i, num int) bool {
return num%2 == 0
}
result, ok := slice.FindLastBy(nums, isEven)
fmt.Println(result)
fmt.Println(ok)
// Output:
// 4
// true
}
```
### <span id="Flatten">Flatten</span>
<p>将切片压平一层</p>
@@ -1003,6 +1079,44 @@ func main() {
}
```
### <span id="ForEachWithBreak">ForEachWithBreak</span>
<p>遍历切片的元素并为每个元素调用iteratee函数当iteratee函数返回false时终止遍历。</p>
<b>函数签名:</b>
```go
func ForEachWithBreak[T any](slice []T, iteratee func(index int, item T) bool)
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
numbers := []int{1, 2, 3, 4, 5}
var sum int
slice.ForEachWithBreak(numbers, func(_, n int) bool {
if n > 3 {
return false
}
sum += n
return true
})
fmt.Println(sum)
// Output:
// 6
}
```
### <span id="GroupBy">GroupBy</span>
<p>迭代切片的元素,每个元素将按条件分组,返回两个切片</p>
@@ -1323,19 +1437,19 @@ import (
func main() {
nums := []int{1, 2, 3, 4, 5}
getEvenNumStr := func(i, num int) (string, bool) {
if num%2 == 0 {
return strconv.FormatInt(int64(num), 10), true
}
return "", false
}
getEvenNumStr := func(i, num int) (string, bool) {
if num%2 == 0 {
return strconv.FormatInt(int64(num), 10), true
}
return "", false
}
result := slice.FilterMap(nums, getEvenNumStr)
result := slice.FilterMap(nums, getEvenNumStr)
fmt.Printf("%#v", result)
fmt.Printf("%#v", result)
// Output:
// []string{"2", "4"}
// Output:
// []string{"2", "4"}
}
```
@@ -1360,15 +1474,15 @@ import (
func main() {
nums := []int{1, 2, 3, 4}
result := slice.FlatMap(nums, func(i int, num int) []string {
s := "hi-" + strconv.FormatInt(int64(num), 10)
return []string{s}
})
result := slice.FlatMap(nums, func(i int, num int) []string {
s := "hi-" + strconv.FormatInt(int64(num), 10)
return []string{s}
})
fmt.Printf("%#v", result)
fmt.Printf("%#v", result)
// Output:
// []string{"hi-1", "hi-2", "hi-3", "hi-4"}
// Output:
// []string{"hi-1", "hi-2", "hi-3", "hi-4"}
}
```
@@ -1435,7 +1549,7 @@ func main() {
### <span id="Reduce">Reduce</span>
<p>将切片中的元素依次运行iteratee函数返回运行结果</p>
<p>将切片中的元素依次运行iteratee函数返回运行结果(废弃建议使用ReduceBy)</p>
<b>函数签名:</b>
@@ -1467,6 +1581,72 @@ func main() {
}
```
### <span id="ReduceBy">ReduceBy</span>
<p>对切片元素执行reduce操作。</p>
<b>函数签名:</b>
```go
func ReduceBy[T any, U any](slice []T, initial U, reducer func(index int, item T, agg U) U) U
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
result1 := slice.ReduceBy([]int{1, 2, 3, 4}, 0, func(_ int, item int, agg int) int {
return agg + item
})
result2 := slice.ReduceBy([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 10
// 1234
}
```
### <span id="ReduceRight">ReduceRight</span>
<p>类似ReduceBy操作迭代切片元素顺序从右至左。</p>
<b>函数签名:</b>
```go
func ReduceRight[T any, U any](slice []T, initial U, reducer func(index int, item T, agg U) U) U
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
result := slice.ReduceRight([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
fmt.Println(result)
// Output:
// 4321
}
```
### <span id="Replace">Replace</span>
<p>返回切片的副本其中前n个不重叠的old替换为new</p>
@@ -1587,8 +1767,8 @@ func main() {
nums := []int{1, 2, 3, 4, 5}
result := slice.Shuffle(nums)
fmt.Println(res)
fmt.Println(res)
// Output:
// [3 1 5 4 2] (random order)
}
@@ -1614,17 +1794,17 @@ import (
func main() {
result1 := slice.IsAscending([]int{1, 2, 3, 4, 5})
result2 := slice.IsAscending([]int{5, 4, 3, 2, 1})
result3 := slice.IsAscending([]int{2, 1, 3, 4, 5})
result2 := slice.IsAscending([]int{5, 4, 3, 2, 1})
result3 := slice.IsAscending([]int{2, 1, 3, 4, 5})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// true
// false
// false
// Output:
// true
// false
// false
}
```
@@ -1648,17 +1828,17 @@ import (
func main() {
result1 := slice.IsDescending([]int{5, 4, 3, 2, 1})
result2 := slice.IsDescending([]int{1, 2, 3, 4, 5})
result3 := slice.IsDescending([]int{2, 1, 3, 4, 5})
result2 := slice.IsDescending([]int{1, 2, 3, 4, 5})
result3 := slice.IsDescending([]int{2, 1, 3, 4, 5})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// true
// false
// false
// Output:
// true
// false
// false
}
```
@@ -1682,17 +1862,17 @@ import (
func main() {
result1 := slice.IsSorted([]int{5, 4, 3, 2, 1})
result2 := slice.IsSorted([]int{1, 2, 3, 4, 5})
result3 := slice.IsSorted([]int{2, 1, 3, 4, 5})
result2 := slice.IsSorted([]int{1, 2, 3, 4, 5})
result3 := slice.IsSorted([]int{2, 1, 3, 4, 5})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// true
// true
// false
// Output:
// true
// true
// false
}
```
@@ -1716,23 +1896,23 @@ import (
func main() {
result1 := slice.IsSortedByKey([]string{"a", "ab", "abc"}, func(s string) int {
return len(s)
})
result2 := slice.IsSortedByKey([]string{"abc", "ab", "a"}, func(s string) int {
return len(s)
})
result3 := slice.IsSortedByKey([]string{"abc", "a", "ab"}, func(s string) int {
return len(s)
})
return len(s)
})
result2 := slice.IsSortedByKey([]string{"abc", "ab", "a"}, func(s string) int {
return len(s)
})
result3 := slice.IsSortedByKey([]string{"abc", "a", "ab"}, func(s string) int {
return len(s)
})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// true
// true
// false
// Output:
// true
// true
// false
}
```

940
docs/stream.md Normal file
View File

@@ -0,0 +1,940 @@
# Stream
Package stream implements a sequence of elements supporting sequential and operations. This package is an experiment to explore if stream in go can work as the way java does. it's feature is very limited.
<div STYLE="page-break-after: always;"></div>
## Source:
- [https://github.com/duke-git/lancet/blob/main/stream/stream.go](https://github.com/duke-git/lancet/blob/main/stream/stream.go)
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/v2/stream"
)
```
<div STYLE="page-break-after: always;"></div>
## Index
- [Of](#Of)
- [FromSlice](#FromSlice)
- [FromChannel](#FromChannel)
- [FromRange](#FromRange)
- [Generate](#Generate)
- [Concat](#Concat)
- [Distinct](#Distinct)
- [Filter](#Filter)
- [Map](#Map)
- [Peek](#Peek)
- [Skip](#Skip)
- [Limit](#Limit)
- [Reverse](#Reverse)
- [Range](#Range)
- [Sorted](#Sorted)
- [ForEach](#ForEach)
- [Reduce](#Reduce)
- [FindFirst](#FindFirst)
- [FindLast](#FindLast)
- [Max](#Max)
- [Min](#Min)
- [AllMatch](#AllMatch)
- [AnyMatch](#AnyMatch)
- [NoneMatch](#NoneMatch)
- [Count](#Count)
- [ToSlice](#ToSlice)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="Of">Of</span>
<p>Creates a stream whose elements are the specified values.</p>
<b>Signature:</b>
```go
func Of[T any](elems ...T) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s := stream.Of(1, 2, 3)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
```
### <span id="FromSlice">FromSlice</span>
<p>Creates a stream from slice.</p>
<b>Signature:</b>
```go
func FromSlice[T any](source []T) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s := stream.FromSlice([]int{1, 2, 3})
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
```
### <span id="FromChannel">FromChannel</span>
<p>Creates a stream from channel.</p>
<b>Signature:</b>
```go
func FromChannel[T any](source <-chan T) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
ch := make(chan int)
go func() {
for i := 1; i < 4; i++ {
ch <- i
}
close(ch)
}()
s := stream.FromChannel(ch)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
```
### <span id="FromRange">FromRange</span>
<p>Creates a number stream from start to end. both start and end are included. [start, end]</p>
<b>Signature:</b>
```go
func FromRange[T constraints.Integer | constraints.Float](start, end, step T) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s := stream.FromRange(1, 5, 1)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3 4 5]
}
```
### <span id="Generate">Generate</span>
<p>Creates a stream where each element is generated by the provided generater function.</p>
<b>Signature:</b>
```go
func Generate[T any](generator func() func() (item T, ok bool)) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
n := 0
max := 4
generator := func() func() (int, bool) {
return func() (int, bool) {
n++
return n, n < max
}
}
s := stream.Generate(generator)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
```
### <span id="Concat">Concat</span>
<p>Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.</p>
<b>Signature:</b>
```go
func Concat[T any](a, b stream[T]) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s1 := stream.FromSlice([]int{1, 2, 3})
s2 := stream.FromSlice([]int{4, 5, 6})
s := Concat(s1, s2)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3 4 5 6]
}
```
### <span id="Distinct">Distinct</span>
<p>Creates returns a stream that removes the duplicated items. <b>Support chainable operation</b></p>
<b>Signature:</b>
```go
func (s stream[T]) Distinct() stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 2, 3, 3, 3})
distinct := original.Distinct()
data1 := original.ToSlice()
data2 := distinct.ToSlice()
fmt.Println(data1)
fmt.Println(data2)
// Output:
// [1 2 2 3 3 3]
// [1 2 3]
}
```
### <span id="Filter">Filter</span>
<p>Returns a stream consisting of the elements of this stream that match the given predicate. <b>Support chainable operation</b></p>
<b>Signature:</b>
```go
func (s stream[T]) Filter(predicate func(item T) bool) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3, 4, 5})
isEven := func(n int) bool {
return n%2 == 0
}
even := original.Filter(isEven)
fmt.Println(even.ToSlice())
// Output:
// [2 4]
}
```
### <span id="Map">Map</span>
<p>Returns a stream consisting of the elements of this stream that apply the given function to elements of stream. <b>Support chainable operation</b></p>
<b>Signature:</b>
```go
func (s stream[T]) Map(mapper func(item T) T) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
addOne := func(n int) int {
return n + 1
}
increament := original.Map(addOne)
fmt.Println(increament.ToSlice())
// Output:
// [2 3 4]
}
```
### <span id="Peek">Peek</span>
<p>Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. <b>Support chainable operation</b></p>
<b>Signature:</b>
```go
func (s stream[T]) Peek(consumer func(item T)) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
data := []string{}
peekStream := original.Peek(func(n int) {
data = append(data, fmt.Sprint("value", n))
})
fmt.Println(original.ToSlice())
fmt.Println(peekStream.ToSlice())
fmt.Println(data)
// Output:
// [1 2 3]
// [1 2 3]
// [value1 value2 value3]
}
```
### <span id="Skip">Skip</span>
<p>Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned. <b>Support chainable operation</b></p>
<b>Signature:</b>
```go
func (s stream[T]) Skip(n int) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3, 4})
s1 := original.Skip(-1)
s2 := original.Skip(0)
s3 := original.Skip(1)
s4 := original.Skip(5)
fmt.Println(s1.ToSlice())
fmt.Println(s2.ToSlice())
fmt.Println(s3.ToSlice())
fmt.Println(s4.ToSlice())
// Output:
// [1 2 3 4]
// [1 2 3 4]
// [2 3 4]
// []
}
```
### <span id="Limit">Limit</span>
<p>Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length. <b>Support chainable operation</b></p>
<b>Signature:</b>
```go
func (s stream[T]) Limit(maxSize int) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3, 4})
s1 := original.Limit(-1)
s2 := original.Limit(0)
s3 := original.Limit(1)
s4 := original.Limit(5)
fmt.Println(s1.ToSlice())
fmt.Println(s2.ToSlice())
fmt.Println(s3.ToSlice())
fmt.Println(s4.ToSlice())
// Output:
// []
// []
// [1]
// [1 2 3 4]
}
```
### <span id="Reverse">Reverse</span>
<p>Returns a stream whose elements are reverse order of given stream. <b>Support chainable operation</b></p>
<b>Signature:</b>
```go
func (s stream[T]) Reverse() stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
reverse := original.Reverse()
fmt.Println(reverse.ToSlice())
// Output:
// [3 2 1]
}
```
### <span id="Range">Range</span>
<p>Returns a stream whose elements are in the range from start(included) to end(excluded) original stream.<b>Support chainable operation</b></p>
<b>Signature:</b>
```go
func (s stream[T]) Range(start, end int) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
s1 := original.Range(0, 0)
s2 := original.Range(0, 1)
s3 := original.Range(0, 3)
s4 := original.Range(1, 2)
fmt.Println(s1.ToSlice())
fmt.Println(s2.ToSlice())
fmt.Println(s3.ToSlice())
fmt.Println(s4.ToSlice())
// Output:
// []
// [1]
// [1 2 3]
// [2]
}
```
### <span id="Sorted">Sorted</span>
<p>Returns a stream consisting of the elements of this stream, sorted according to the provided less function.<b>Support chainable operation</b></p>
<b>Signature:</b>
```go
func (s stream[T]) Sorted(less func(a, b T) bool) stream[T]
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{4, 2, 1, 3})
sorted := original.Sorted(func(a, b int) bool { return a < b })
fmt.Println(original.ToSlice())
fmt.Println(sorted.ToSlice())
// Output:
// [4 2 1 3]
// [1 2 3 4]
}
```
### <span id="ForEach">ForEach</span>
<p>Performs an action for each element of this stream.</p>
<b>Signature:</b>
```go
func (s stream[T]) ForEach(action func(item T))
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result := 0
original.ForEach(func(item int) {
result += item
})
fmt.Println(result)
// Output:
// 6
}
```
### <span id="Reduce">Reduce</span>
<p>Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.</p>
<b>Signature:</b>
```go
func (s stream[T]) Reduce(initial T, accumulator func(a, b T) T) T
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result := original.Reduce(0, func(a, b int) int {
return a + b
})
fmt.Println(result)
// Output:
// 6
}
```
### <span id="FindFirst">FindFirst</span>
<p>Returns the first element of this stream and true, or zero value and false if the stream is empty.</p>
<b>Signature:</b>
```go
func (s stream[T]) FindFirst() (T, bool)
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result, ok := original.FindFirst()
fmt.Println(result)
fmt.Println(ok)
// Output:
// 1
// true
}
```
### <span id="FindLast">FindLast</span>
<p>Returns the last element of this stream and true, or zero value and false if the stream is empty.</p>
<b>Signature:</b>
```go
func (s stream[T]) FindLast() (T, bool)
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := FromSlice([]int{3, 2, 1})
result, ok := original.FindLast()
fmt.Println(result)
fmt.Println(ok)
// Output:
// 1
// true
}
```
### <span id="Max">Max</span>
<p>Returns the maximum element of this stream according to the provided less function. less fuction: a > b</p>
<b>Signature:</b>
```go
func (s stream[T]) Max(less func(a, b T) bool) (T, bool)
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{4, 2, 1, 3})
max, ok := original.Max(func(a, b int) bool { return a > b })
fmt.Println(max)
fmt.Println(ok)
// Output:
// 4
// true
}
```
### <span id="Min">Min</span>
<p>Returns the minimum element of this stream according to the provided less function. less fuction: a < b</p>
<b>Signature:</b>
```go
func (s stream[T]) Min(less func(a, b T) bool) (T, bool)
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{4, 2, 1, 3})
min, ok := original.Min(func(a, b int) bool { return a < b })
fmt.Println(min)
fmt.Println(ok)
// Output:
// 1
// true
}
```
### <span id="AllMatch">AllMatch</span>
<p>Returns whether all elements of this stream match the provided predicate.</p>
<b>Signature:</b>
```go
func (s stream[T]) AllMatch(predicate func(item T) bool) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result1 := original.AllMatch(func(item int) bool {
return item > 0
})
result2 := original.AllMatch(func(item int) bool {
return item > 1
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="AnyMatch">AnyMatch</span>
<p>Returns whether any elements of this stream match the provided predicate.</p>
<b>Signature:</b>
```go
func (s stream[T]) AnyMatch(predicate func(item T) bool) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result1 := original.AnyMatch(func(item int) bool {
return item > 1
})
result2 := original.AnyMatch(func(item int) bool {
return item > 3
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="NoneMatch">NoneMatch</span>
<p>Returns whether no elements of this stream match the provided predicate.</p>
<b>Signature:</b>
```go
func (s stream[T]) NoneMatch(predicate func(item T) bool) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result1 := original.NoneMatch(func(item int) bool {
return item > 3
})
result2 := original.NoneMatch(func(item int) bool {
return item > 1
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="Count">Count</span>
<p>Returns the count of elements in the stream.</p>
<b>Signature:</b>
```go
func (s stream[T]) Count() int
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s1 := stream.FromSlice([]int{1, 2, 3})
s2 := stream.FromSlice([]int{})
fmt.Println(s1.Count())
fmt.Println(s2.Count())
// Output:
// 3
// 0
}
```
### <span id="ToSlice">ToSlice</span>
<p>Returns the elements in the stream.</p>
<b>Signature:</b>
```go
func (s stream[T]) ToSlice() []T
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s := stream.Of(1, 2, 3)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
```

940
docs/stream_zh-CN.md Normal file
View File

@@ -0,0 +1,940 @@
# Stream
Stream 流,该包仅验证简单 stream 实现,功能有限。
<div STYLE="page-break-after: always;"></div>
## 源码:
- [https://github.com/duke-git/lancet/blob/main/stream/stream.go](https://github.com/duke-git/lancet/blob/main/stream/stream.go)
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/v2/stream"
)
```
<div STYLE="page-break-after: always;"></div>
## 目录
- [Of](#Of)
- [FromSlice](#FromSlice)
- [FromChannel](#FromChannel)
- [FromRange](#FromRange)
- [Generate](#Generate)
- [Concat](#Concat)
- [Distinct](#Distinct)
- [Filter](#Filter)
- [Map](#Map)
- [Peek](#Peek)
- [Skip](#Skip)
- [Limit](#Limit)
- [Reverse](#Reverse)
- [Range](#Range)
- [Sorted](#Sorted)
- [ForEach](#ForEach)
- [Reduce](#Reduce)
- [FindFirst](#FindFirst)
- [FindLast](#FindLast)
- [Max](#Max)
- [Min](#Min)
- [AllMatch](#AllMatch)
- [AnyMatch](#AnyMatch)
- [NoneMatch](#NoneMatch)
- [Count](#Count)
- [ToSlice](#ToSlice)
<div STYLE="page-break-after: always;"></div>
## 文档
### <span id="Of">Of</span>
<p>创建元素为指定值的stream。</p>
<b>函数签名:</b>
```go
func Of[T any](elems ...T) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s := stream.Of(1, 2, 3)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
```
### <span id="FromSlice">FromSlice</span>
<p>从切片创建stream。</p>
<b>函数签名:</b>
```go
func FromSlice[T any](source []T) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s := stream.FromSlice([]int{1, 2, 3})
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
```
### <span id="FromChannel">FromChannel</span>
<p>从通道创建stream。</p>
<b>函数签名:</b>
```go
func FromChannel[T any](source <-chan T) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
ch := make(chan int)
go func() {
for i := 1; i < 4; i++ {
ch <- i
}
close(ch)
}()
s := stream.FromChannel(ch)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
```
### <span id="FromRange">FromRange</span>
<p>指定一个范围创建stream, 范围两端点值都包括在内。</p>
<b>函数签名:</b>
```go
func FromRange[T constraints.Integer | constraints.Float](start, end, step T) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s := stream.FromRange(1, 5, 1)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3 4 5]
}
```
### <span id="Generate">Generate</span>
<p>创建一个stream其中每个元素都由提供的生成器函数生成</p>
<b>函数签名:</b>
```go
func Generate[T any](generator func() func() (item T, ok bool)) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
n := 0
max := 4
generator := func() func() (int, bool) {
return func() (int, bool) {
n++
return n, n < max
}
}
s := stream.Generate(generator)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
```
### <span id="Concat">Concat</span>
<p>创建一个延迟连接stream其元素是第一个stream的所有元素后跟第二个stream的全部元素。</p>
<b>函数签名:</b>
```go
func Concat[T any](a, b stream[T]) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s1 := stream.FromSlice([]int{1, 2, 3})
s2 := stream.FromSlice([]int{4, 5, 6})
s := Concat(s1, s2)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3 4 5 6]
}
```
### <span id="Distinct">Distinct</span>
<p>创建并返回一个stream用于删除重复的项。 <b>支持链式操作</b></p>
<b>函数签名:</b>
```go
func (s stream[T]) Distinct() stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 2, 3, 3, 3})
distinct := original.Distinct()
data1 := original.ToSlice()
data2 := distinct.ToSlice()
fmt.Println(data1)
fmt.Println(data2)
// Output:
// [1 2 2 3 3 3]
// [1 2 3]
}
```
### <span id="Filter">Filter</span>
<p>返回一个通过判定函数的stream <b>支持链式操作</b></p>
<b>函数签名:</b>
```go
func (s stream[T]) Filter(predicate func(item T) bool) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3, 4, 5})
isEven := func(n int) bool {
return n%2 == 0
}
even := original.Filter(isEven)
fmt.Println(even.ToSlice())
// Output:
// [2 4]
}
```
### <span id="Map">Map</span>
<p>返回一个stream该stream由将给定函数应用于源stream元素的元素组成。<b>支持链式操作</b></p>
<b>函数签名:</b>
```go
func (s stream[T]) Map(mapper func(item T) T) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
addOne := func(n int) int {
return n + 1
}
increament := original.Map(addOne)
fmt.Println(increament.ToSlice())
// Output:
// [2 3 4]
}
```
### <span id="Peek">Peek</span>
<p>返回一个由源stream的元素组成的stream并在从生成的stream中消耗元素时对每个元素执行所提供的操作。 <b>支持链式操作</b></p>
<b>函数签名:</b>
```go
func (s stream[T]) Peek(consumer func(item T)) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
data := []string{}
peekStream := original.Peek(func(n int) {
data = append(data, fmt.Sprint("value", n))
})
fmt.Println(original.ToSlice())
fmt.Println(peekStream.ToSlice())
fmt.Println(data)
// Output:
// [1 2 3]
// [1 2 3]
// [value1 value2 value3]
}
```
### <span id="Skip">Skip</span>
<p>在丢弃stream的前n个元素后返回由源stream的其余元素组成的stream。如果此stream包含的元素少于n个则将返回一个空stream。<b>支持链式操作</b></p>
<b>函数签名:</b>
```go
func (s stream[T]) Skip(n int) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3, 4})
s1 := original.Skip(-1)
s2 := original.Skip(0)
s3 := original.Skip(1)
s4 := original.Skip(5)
fmt.Println(s1.ToSlice())
fmt.Println(s2.ToSlice())
fmt.Println(s3.ToSlice())
fmt.Println(s4.ToSlice())
// Output:
// [1 2 3 4]
// [1 2 3 4]
// [2 3 4]
// []
}
```
### <span id="Limit">Limit</span>
<p>返回由源stream的元素组成的stream该stream被截断为长度不超过maxSize。<b>支持链式操作</b></p>
<b>函数签名:</b>
```go
func (s stream[T]) Limit(maxSize int) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3, 4})
s1 := original.Limit(-1)
s2 := original.Limit(0)
s3 := original.Limit(1)
s4 := original.Limit(5)
fmt.Println(s1.ToSlice())
fmt.Println(s2.ToSlice())
fmt.Println(s3.ToSlice())
fmt.Println(s4.ToSlice())
// Output:
// []
// []
// [1]
// [1 2 3 4]
}
```
### <span id="Reverse">Reverse</span>
<p>返回元素与源stream的顺序相反的stream。<b>支持链式操作</b></p>
<b>函数签名:</b>
```go
func (s stream[T]) Reverse() stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
reverse := original.Reverse()
fmt.Println(reverse.ToSlice())
// Output:
// [3 2 1]
}
```
### <span id="Range">Range</span>
<p>返回一个stream该stream的元素在从源stream的开始包含到结束排除的范围内。<b>支持链式操作</b></p>
<b>函数签名:</b>
```go
func (s stream[T]) Range(start, end int) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
s1 := original.Range(0, 0)
s2 := original.Range(0, 1)
s3 := original.Range(0, 3)
s4 := original.Range(1, 2)
fmt.Println(s1.ToSlice())
fmt.Println(s2.ToSlice())
fmt.Println(s3.ToSlice())
fmt.Println(s4.ToSlice())
// Output:
// []
// [1]
// [1 2 3]
// [2]
}
```
### <span id="Sorted">Sorted</span>
<p>返回一个stream该stream由源stream的元素组成并根据提供的less函数进行排序。<b>支持链式操作</b></p>
<b>函数签名:</b>
```go
func (s stream[T]) Sorted(less func(a, b T) bool) stream[T]
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{4, 2, 1, 3})
sorted := original.Sorted(func(a, b int) bool { return a < b })
fmt.Println(original.ToSlice())
fmt.Println(sorted.ToSlice())
// Output:
// [4 2 1 3]
// [1 2 3 4]
}
```
### <span id="ForEach">ForEach</span>
<p>对stream的每个元素执行一个操作。</p>
<b>函数签名:</b>
```go
func (s stream[T]) ForEach(action func(item T))
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result := 0
original.ForEach(func(item int) {
result += item
})
fmt.Println(result)
// Output:
// 6
}
```
### <span id="Reduce">Reduce</span>
<p>使用关联累加函数对stream的元素执行reduce操作并reduce操作结果如果有。</p>
<b>函数签名:</b>
```go
func (s stream[T]) Reduce(initial T, accumulator func(a, b T) T) T
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result := original.Reduce(0, func(a, b int) int {
return a + b
})
fmt.Println(result)
// Output:
// 6
}
```
### <span id="FindFirst">FindFirst</span>
<p>返回此stream的第一个元素和true如果stream为空则返回零值和false。</p>
<b>函数签名:</b>
```go
func (s stream[T]) FindFirst() (T, bool)
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result, ok := original.FindFirst()
fmt.Println(result)
fmt.Println(ok)
// Output:
// 1
// true
}
```
### <span id="FindLast">FindLast</span>
<p>返回此stream最后一个元素和true如果stream为空则返回零值和false。</p>
<b>函数签名:</b>
```go
func (s stream[T]) FindLast() (T, bool)
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := FromSlice([]int{3, 2, 1})
result, ok := original.FindLast()
fmt.Println(result)
fmt.Println(ok)
// Output:
// 1
// true
}
```
### <span id="Max">Max</span>
<p>根据提供的less函数返回stream的最大元素。less 函数: a > b</p>
<b>函数签名:</b>
```go
func (s stream[T]) Max(less func(a, b T) bool) (T, bool)
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{4, 2, 1, 3})
max, ok := original.Max(func(a, b int) bool { return a > b })
fmt.Println(max)
fmt.Println(ok)
// Output:
// 4
// true
}
```
### <span id="Min">Min</span>
<p>根据提供的less函数返回stream的最小元素。less函数: a < b</p>
<b>函数签名:</b>
```go
func (s stream[T]) Min(less func(a, b T) bool) (T, bool)
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{4, 2, 1, 3})
min, ok := original.Min(func(a, b int) bool { return a < b })
fmt.Println(min)
fmt.Println(ok)
// Output:
// 1
// true
}
```
### <span id="AllMatch">AllMatch</span>
<p>判断stream的所有元素是否全部匹配指定判定函数。</p>
<b>函数签名:</b>
```go
func (s stream[T]) AllMatch(predicate func(item T) bool) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result1 := original.AllMatch(func(item int) bool {
return item > 0
})
result2 := original.AllMatch(func(item int) bool {
return item > 1
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="AnyMatch">AnyMatch</span>
<p>判断stream是否包含匹配指定判定函数的元素。</p>
<b>函数签名:</b>
```go
func (s stream[T]) AnyMatch(predicate func(item T) bool) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result1 := original.AnyMatch(func(item int) bool {
return item > 1
})
result2 := original.AnyMatch(func(item int) bool {
return item > 3
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="NoneMatch">NoneMatch</span>
<p>判断stream的元素是否全部不匹配指定的判定函数。</p>
<b>函数签名:</b>
```go
func (s stream[T]) NoneMatch(predicate func(item T) bool) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
original := stream.FromSlice([]int{1, 2, 3})
result1 := original.NoneMatch(func(item int) bool {
return item > 3
})
result2 := original.NoneMatch(func(item int) bool {
return item > 1
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="Count">Count</span>
<p>返回stream中元素的数量。</p>
<b>函数签名:</b>
```go
func (s stream[T]) Count() int
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s1 := stream.FromSlice([]int{1, 2, 3})
s2 := stream.FromSlice([]int{})
fmt.Println(s1.Count())
fmt.Println(s2.Count())
// Output:
// 3
// 0
}
```
### <span id="ToSlice">ToSlice</span>
<p>返回stream中的元素切片。</p>
<b>函数签名:</b>
```go
func (s stream[T]) ToSlice() []T
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/stream"
)
func main() {
s := stream.Of(1, 2, 3)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
```

353
docs/structs/field.md Normal file
View File

@@ -0,0 +1,353 @@
# Field
Field is abstract struct field for provide several high level functions
<div STYLE="page-break-after: always;"></div>
## Source:
- [https://github.com/duke-git/lancet/blob/main/structs/field.go](https://github.com/duke-git/lancet/blob/main/structs/field.go)
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/v2/structs"
)
```
<div STYLE="page-break-after: always;"></div>
## Index:
- [Tag](#Tag)
- [Name](#Name)
- [Value](#Value)
- [Kind](#Kind)
- [IsEmbedded](#IsEmbedded)
- [IsExported](#IsExported)
- [IsZero](#IsZero)
- [IsSlice](#IsSlice)
> NoteSince `Field` inherits from `Struct`, it also has all the methods of 'Struct', as follows:
- [ToMap](https://github.com/duke-git/lancet/blob/main/docs/structs/struct.md#ToMap)
- [Fields](https://github.com/duke-git/lancet/blob/main/docs/structs/struct.md#Fields)
- [Field](https://github.com/duke-git/lancet/blob/main/docs/structs/struct.md#Field)
- [IsStruct](https://github.com/duke-git/lancet/blob/main/docs/structs/struct.md#IsStruct)
<div STYLE="page-break-after: always;"></div>
## Documentation:
### <span id="Tag">Tag</span>
<p>Get a `Tag` of the `Field`, `Tag` is a abstract struct field tag</p>
<b>Signature:</b>
```go
func (f *Field) Tag() *Tag
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string `json:"name,omitempty"`
}
p1 := &Parent{"111"}
s := structs.New(p1)
n, _ := s.Field("Name")
tag := n.Tag()
fmt.Println(tag.Name)
// Output:
// name
}
```
### <span id="Value">Value</span>
<p>Get the `Field` underlying value</p>
<b>Signature:</b>
```go
func (f *Field) Value() any
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string `json:"name,omitempty"`
}
p1 := &Parent{"111"}
s := structs.New(p1)
n, _ := s.Field("Name")
fmt.Println(n.Value())
// Output:
// 111
}
```
### <span id="IsEmbedded">IsEmbedded</span>
<p>Check if the field is an embedded field</p>
<b>Signature:</b>
```go
func (f *Field) IsEmbedded() bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
}
type Child struct {
Parent
Age int
}
c1 := &Child{}
c1.Name = "111"
c1.Age = 11
s := structs.New(c1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
fmt.Println(n.IsEmbedded())
fmt.Println(a.IsEmbedded())
// Output:
// true
// false
}
```
### <span id="IsExported">IsExported</span>
<p>Check if the field is exported</p>
<b>Signature:</b>
```go
func (f *Field) IsExported() bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
age int
}
p1 := &Parent{Name: "11", age: 11}
s := structs.New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("age")
fmt.Println(n.IsExported())
fmt.Println(a.IsExported())
// Output:
// true
// false
}
```
### <span id="IsZero">IsZero</span>
<p>Check if the field is zero value</p>
<b>Signature:</b>
```go
func (f *Field) IsZero() bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
Age int
}
p1 := &Parent{Age: 11}
s := structs.New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
fmt.Println(n.IsZero())
fmt.Println(a.IsZero())
// Output:
// true
// false
}
```
### <span id="Name">Name</span>
<p>Get the field name</p>
<b>Signature:</b>
```go
func (f *Field) Name() string
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
Age int
}
p1 := &Parent{Age: 11}
s := structs.New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
fmt.Println(n.Name())
fmt.Println(a.Name())
// Output:
// Name
// Age
}
```
### <span id="Kind">Kind</span>
<p>Get the field's kind</p>
<b>Signature:</b>
```go
func (f *Field) Kind() reflect.Kind
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
Age int
}
p1 := &Parent{Age: 11}
s := structs.New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
fmt.Println(n.Kind())
fmt.Println(a.Kind())
// Output:
// string
// int
}
```
### <span id="IsSlice">IsSlice</span>
<p>Check if the field is a slice</p>
<b>Signature:</b>
```go
func (f *Field) IsSlice() bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
arr []int
}
p1 := &Parent{arr: []int{1, 2, 3}}
s := structs.New(p1)
a, _ := s.Field("arr")
fmt.Println(a.IsSlice())
// Output:
// true
}
```

353
docs/structs/field_zh-CN.md Normal file
View File

@@ -0,0 +1,353 @@
# Field
Field 包封装了一个抽象的`Field`结构体,提供了操作`struct`属性的相关函数
<div STYLE="page-break-after: always;"></div>
## 源码:
- [https://github.com/duke-git/lancet/blob/main/structs/field.go](https://github.com/duke-git/lancet/blob/main/structs/field.go)
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/v2/structs"
)
```
<div STYLE="page-break-after: always;"></div>
## 目录:
- [Tag](#Tag)
- [Name](#Name)
- [Value](#Value)
- [Kind](#Kind)
- [IsEmbedded](#IsEmbedded)
- [IsExported](#IsExported)
- [IsZero](#IsZero)
- [IsSlice](#IsSlice)
> 注意:由于`Field`继承于`Struct`,所以同样拥有`Struct`所有方法,如下:
- [ToMap](https://github.com/duke-git/lancet/blob/main/docs/structs/struct_zh-CN.md#ToMap)
- [Fields](https://github.com/duke-git/lancet/blob/main/docs/structs/struct_zh-CN.md#Fields)
- [Field](https://github.com/duke-git/lancet/blob/main/docs/structs/struct_zh-CN.md#Field)
- [IsStruct](https://github.com/duke-git/lancet/blob/main/docs/structs/struct_zh-CN.md#IsStruct)
<div STYLE="page-break-after: always;"></div>
## API 文档:
### <span id="Tag">Tag</span>
<p>获取`Field``Tag`默认的tag key是json</p>
<b>函数签名:</b>
```go
func (f *Field) Tag() *Tag
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string `json:"name,omitempty"`
}
p1 := &Parent{"111"}
s := structs.New(p1)
n, _ := s.Field("Name")
tag := n.Tag()
fmt.Println(tag.Name)
// Output:
// name
}
```
### <span id="Value">Value</span>
<p>获取`Field`属性的值</p>
<b>函数签名:</b>
```go
func (f *Field) Value() any
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string `json:"name,omitempty"`
}
p1 := &Parent{"111"}
s := structs.New(p1)
n, _ := s.Field("Name")
fmt.Println(n.Value())
// Output:
// 111
}
```
### <span id="IsEmbedded">IsEmbedded</span>
<p>判断属性是否为嵌入</p>
<b>函数签名:</b>
```go
func (f *Field) IsEmbedded() bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
}
type Child struct {
Parent
Age int
}
c1 := &Child{}
c1.Name = "111"
c1.Age = 11
s := structs.New(c1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
fmt.Println(n.IsEmbedded())
fmt.Println(a.IsEmbedded())
// Output:
// true
// false
}
```
### <span id="IsExported">IsExported</span>
<p>判断属性是否导出</p>
<b>函数签名:</b>
```go
func (f *Field) IsExported() bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
age int
}
p1 := &Parent{Name: "11", age: 11}
s := structs.New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("age")
fmt.Println(n.IsExported())
fmt.Println(a.IsExported())
// Output:
// true
// false
}
```
### <span id="IsZero">IsZero</span>
<p>判断属性是否为零值</p>
<b>函数签名:</b>
```go
func (f *Field) IsZero() bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
Age int
}
p1 := &Parent{Age: 11}
s := structs.New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
fmt.Println(n.IsZero())
fmt.Println(a.IsZero())
// Output:
// true
// false
}
```
### <span id="Name">Name</span>
<p>获取属性名</p>
<b>函数签名:</b>
```go
func (f *Field) Name() string
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
Age int
}
p1 := &Parent{Age: 11}
s := structs.New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
fmt.Println(n.Name())
fmt.Println(a.Name())
// Output:
// Name
// Age
}
```
### <span id="Kind">Kind</span>
<p>获取属性Kind</p>
<b>函数签名:</b>
```go
func (f *Field) Kind() reflect.Kind
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
Age int
}
p1 := &Parent{Age: 11}
s := structs.New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
fmt.Println(n.Kind())
fmt.Println(a.Kind())
// Output:
// string
// int
}
```
### <span id="IsSlice">IsSlice</span>
<p>判断属性是否是切片</p>
<b>函数签名:</b>
```go
func (f *Field) IsSlice() bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
arr []int
}
p1 := &Parent{arr: []int{1, 2, 3}}
s := structs.New(p1)
a, _ := s.Field("arr")
fmt.Println(a.IsSlice())
// Output:
// true
}
```

213
docs/structs/struct.md Normal file
View File

@@ -0,0 +1,213 @@
# Structs
Struct is abstract struct for provide several high level functions
<div STYLE="page-break-after: always;"></div>
## Source:
- [https://github.com/duke-git/lancet/blob/main/structs/struct.go](https://github.com/duke-git/lancet/blob/main/structs/struct.go)
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/v2/structs"
)
```
<div STYLE="page-break-after: always;"></div>
## Index:
- [New](#New)
- [ToMap](#ToMap)
- [Fields](#Fields)
- [Field](#Field)
- [IsStruct](#IsStruct)
<div STYLE="page-break-after: always;"></div>
## Documentation:
### <span id="New">New</span>
<p>The constructor function of the `Struct` </p>
<b>Signature:</b>
```go
func New(value any, tagName ...string) *Struct
```
<b>Example:</b>
```go
package main
import (
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type People struct {
Name string `json:"name"`
}
p1 := &People{Name: "11"}
s := structs.New(p1)
// to do something
}
```
### <span id="ToMap">ToMap</span>
<p>convert a valid struct to a map</p>
<b>Signature:</b>
```go
func (s *Struct) ToMap() (map[string]any, error)
```
> In addition, provided a convenient static function ToMap
```go
func ToMap(v any) (map[string]any, error)
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type People struct {
Name string `json:"name"`
}
p1 := &People{Name: "11"}
// use constructor function
s1 := structs.New(p1)
m1, _ := s1.ToMap()
fmt.Println(m1)
// use static function
m2, _ := structs.ToMap(p1)
fmt.Println(m2)
// Output:
// map[name:11]
// map[name:11]
}
```
### <span id="Fields">Fields</span>
<p>Get all fields of a given struct, that the fields are abstract struct field</p>
<b>Signature:</b>
```go
func (s *Struct) Fields() []*Field
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type People struct {
Name string `json:"name"`
}
p1 := &People{Name: "11"}
s := structs.New(p1)
fields := s.Fields()
fmt.Println(len(fields))
// Output:
// 1
}
```
### <span id="Field">Field</span>
<p>Get an abstract field of a struct by given field name </p>
<b>Signature:</b>
```go
func (s *Struct) Field(name string) *Field
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type People struct {
Name string `json:"name"`
}
p1 := &People{Name: "11"}
s := structs.New(p1)
f := s.Field("Name")
fmt.Println(f.Value())
// Output:
// 11
}
```
### <span id="IsStruct">IsStruct</span>
<p>Check if the struct is valid</p>
<b>Signature:</b>
```go
func (s *Struct) IsStruct() bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type People struct {
Name string `json:"name"`
}
p1 := &People{Name: "11"}
s := structs.New(p1)
fmt.Println(s.IsStruct())
// Output:
// true
}
```

View File

@@ -0,0 +1,212 @@
# Structs
structs 包封装了一个抽象的`Struct`结构体,提供了操作`struct`的相关函数
<div STYLE="page-break-after: always;"></div>
## 源码:
- [https://github.com/duke-git/lancet/blob/main/structs/struct.go](https://github.com/duke-git/lancet/blob/main/structs/struct.go)
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/v2/structs"
)
```
<div STYLE="page-break-after: always;"></div>
## 目录:
- [New](#New)
- [ToMap](#ToMap)
- [Fields](#Fields)
- [Field](#Field)
- [IsStruct](#IsStruct)
<div STYLE="page-break-after: always;"></div>
## API 文档:
### <span id="New">New</span>
<p>`Struct`结构体的构造函数</p>
<b>函数签名:</b>
```go
func New(value any, tagName ...string) *Struct
```
<b>示例:</b>
```go
package main
import (
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type People struct {
Name string `json:"name"`
}
p1 := &People{Name: "11"}
s := structs.New(p1)
// to do something
}
```
### <span id="ToMap">ToMap</span>
<p>将一个合法的struct对象转换为map[string]any</p>
<b>函数签名:</b>
```go
func (s *Struct) ToMap() (map[string]any, error)
```
<b>除此之外提供一个便捷的静态方法ToMap</b>
```go
func ToMap(v any) (map[string]any, error)
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type People struct {
Name string `json:"name"`
}
p1 := &People{Name: "11"}
s1 := structs.New(p1)
m1, _ := s1.ToMap()
fmt.Println(m1)
// 如果不需要Struct更多的方法可以直接使用ToMap
m2, _ := structs.ToMap(p1)
fmt.Println(m2)
// Output:
// map[name:11]
// map[name:11]
}
```
### <span id="Fields">Fields</span>
<p>获取一个struct对象的属性列表</p>
<b>函数签名:</b>
```go
func (s *Struct) Fields() []*Field
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type People struct {
Name string `json:"name"`
}
p1 := &People{Name: "11"}
s := structs.New(p1)
fields := s.Fields()
fmt.Println(len(fields))
// Output:
// 1
}
```
### <span id="Field">Field</span>
<p>根据属性名获取一个struct对象的属性</p>
<b>函数签名:</b>
```go
func (s *Struct) Field(name string) *Field
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type People struct {
Name string `json:"name"`
}
p1 := &People{Name: "11"}
s := structs.New(p1)
f := s.Field("Name")
fmt.Println(f.Value())
// Output:
// 11
}
```
### <span id="IsStruct">IsStruct</span>
<p>判断是否为一个合法的struct对象</p>
<b>函数签名:</b>
```go
func (s *Struct) IsStruct() bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type People struct {
Name string `json:"name"`
}
p1 := &People{Name: "11"}
s := structs.New(p1)
fmt.Println(s.IsStruct())
// Output:
// true
}
```

View File

@@ -45,6 +45,16 @@ import (
- [Unwrap](#Unwrap)
- [SplitWords](#SplitWords)
- [WordCount](#WordCount)
- [RemoveNonPrintable](#RemoveNonPrintable)
- [StringToBytes](#StringToBytes)
- [BytesToString](#BytesToString)
- [IsBlank](#IsBlank)
- [HasPrefixAny](#HasPrefixAny)
- [HasSuffixAny](#HasSuffixAny)
- [IndexOffset](#IndexOffset)
- [ReplaceWithMap](#ReplaceWithMap)
- [Trim](#Trim)
- [SplitAndTrim](#SplitAndTrim)
<div STYLE="page-break-after: always;"></div>
@@ -851,7 +861,6 @@ func main() {
}
```
### <span id="SplitWords">SplitWords</span>
<p>Splits a string into words, word only contains alphabetic characters.</p>
@@ -895,7 +904,6 @@ func main() {
}
```
### <span id="WordCount">WordCount</span>
<p>Return the number of meaningful word, word only contains alphabetic characters.</p>
@@ -937,4 +945,337 @@ func main() {
// 0
// 0
}
```
```
### <span id="RemoveNonPrintable">RemoveNonPrintable</span>
<p>Remove non-printable characters from a string.</p>
<b>Signature:</b>
```go
func RemoveNonPrintable(str string) string
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.RemoveNonPrintable("hello\u00a0 \u200bworld\n")
result2 := strutil.RemoveNonPrintable("你好😄")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// hello world
// 你好😄
}
```
### <span id="StringToBytes">StringToBytes</span>
<p>Converts a string to byte slice without a memory allocation.</p>
<b>Signature:</b>
```go
func StringToBytes(str string) (b []byte)
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.StringToBytes("abc")
result2 := reflect.DeepEqual(result1, []byte{'a', 'b', 'c'})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// [97 98 99]
// true
}
```
### <span id="BytesToString">BytesToString</span>
<p>Converts a byte slice to string without a memory allocation.</p>
<b>Signature:</b>
```go
func BytesToString(bytes []byte) string
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
bytes := []byte{'a', 'b', 'c'}
result := strutil.BytesToString(bytes)
fmt.Println(result)
// Output:
// abc
}
```
### <span id="IsBlank">IsBlank</span>
<p>Checks if a string is whitespace or empty.</p>
<b>Signature:</b>
```go
func IsBlank(str string) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.IsBlank("")
result2 := strutil.IsBlank("\t\v\f\n")
result3 := strutil.IsBlank(" 中文")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// true
// true
// false
}
```
### <span id="HasPrefixAny">HasPrefixAny</span>
<p>Checks if a string starts with any of an array of specified strings.</p>
<b>Signature:</b>
```go
func ReplaceWithMap(str string, replaces map[string]string) string
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.HasPrefixAny("foo bar", []string{"fo", "xyz", "hello"})
result2 := strutil.HasPrefixAny("foo bar", []string{"oom", "world"})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="HasSuffixAny">HasSuffixAny</span>
<p>Checks if a string ends with any of an array of specified strings.</p>
<b>Signature:</b>
```go
func HasSuffixAny(str string, suffixes []string) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.HasSuffixAny("foo bar", []string{"bar", "xyz", "hello"})
result2 := strutil.HasSuffixAny("foo bar", []string{"oom", "world"})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="IndexOffset">IndexOffset</span>
<p>Returns the index of the first instance of substr in string after offsetting the string by `idxFrom`, or -1 if substr is not present in string.</p>
<b>Signature:</b>
```go
func IndexOffset(str string, substr string, idxFrom int) int
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
str := "foo bar hello world"
result1 := strutil.IndexOffset(str, "o", 5)
result2 := strutil.IndexOffset(str, "o", 0)
result3 := strutil.IndexOffset(str, "d", len(str)-1)
result4 := strutil.IndexOffset(str, "d", len(str))
result5 := strutil.IndexOffset(str, "f", -1)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// 12
// 1
// 18
// -1
// -1
}
```
### <span id="ReplaceWithMap">ReplaceWithMap</span>
<p>Returns a copy of `str`, which is replaced by a map in unordered way, case-sensitively.</p>
<b>Signature:</b>
```go
func ReplaceWithMap(str string, replaces map[string]string) string
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
str := "ac ab ab ac"
replaces := map[string]string{
"a": "1",
"b": "2",
}
result := strutil.ReplaceWithMap(str, replaces)
fmt.Println(result)
// Output:
// 1c 12 12 1c
}
```
### <span id="Trim">Trim</span>
<p>Strips whitespace (or other characters) from the beginning and end of a string. The optional parameter `characterMask` specifies the additional stripped characters.</p>
<b>Signature:</b>
```go
func Trim(str string, characterMask ...string) string
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.Trim("\nabcd")
str := "$ ab cd $ "
result2 := strutil.Trim(str)
result3 := strutil.Trim(str, "$")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// abcd
// $ ab cd $
// ab cd
}
```
### <span id="SplitAndTrim">SplitAndTrim</span>
<p>Splits string `str` by a string `delimiter` to a slice, and calls Trim to every element of slice. It ignores the elements which are empty after Trim.</p>
<b>Signature:</b>
```go
func SplitAndTrim(str, delimiter string, characterMask ...string) []string
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
str := " a,b, c,d,$1 "
result1 := strutil.SplitAndTrim(str, ",")
result2 := strutil.SplitAndTrim(str, ",", "$")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// [a b c d $1]
// [a b c d 1]
}
```

View File

@@ -45,6 +45,16 @@ import (
- [Unwrap](#Unwrap)
- [SplitWords](#SplitWords)
- [WordCount](#WordCount)
- [RemoveNonPrintable](#RemoveNonPrintable)
- [StringToBytes](#StringToBytes)
- [BytesToString](#BytesToString)
- [IsBlank](#IsBlank)
- [HasPrefixAny](#HasPrefixAny)
- [HasSuffixAny](#HasSuffixAny)
- [IndexOffset](#IndexOffset)
- [ReplaceWithMap](#ReplaceWithMap)
- [Trim](#Trim)
- [SplitAndTrim](#SplitAndTrim)
<div STYLE="page-break-after: always;"></div>
@@ -894,7 +904,6 @@ func main() {
}
```
### <span id="WordCount">WordCount</span>
<p>返回有意义单词的数量,只支持字母字符单词。</p>
@@ -936,4 +945,337 @@ func main() {
// 0
// 0
}
```
```
### <span id="RemoveNonPrintable">RemoveNonPrintable</span>
<p>删除字符串中不可打印的字符。</p>
<b>函数签名:</b>
```go
func RemoveNonPrintable(str string) string
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.RemoveNonPrintable("hello\u00a0 \u200bworld\n")
result2 := strutil.RemoveNonPrintable("你好😄")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// hello world
// 你好😄
}
```
### <span id="StringToBytes">StringToBytes</span>
<p>在不分配内存的情况下将字符串转换为字节片。</p>
<b>函数签名:</b>
```go
func StringToBytes(str string) (b []byte)
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.StringToBytes("abc")
result2 := reflect.DeepEqual(result1, []byte{'a', 'b', 'c'})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// [97 98 99]
// true
}
```
### <span id="BytesToString">BytesToString</span>
<p>在不分配内存的情况下将字节切片转换为字符串。</p>
<b>函数签名:</b>
```go
func BytesToString(bytes []byte) string
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
bytes := []byte{'a', 'b', 'c'}
result := strutil.BytesToString(bytes)
fmt.Println(result)
// Output:
// abc
}
```
### <span id="IsBlank">IsBlank</span>
<p>检查字符串是否为空格或空。</p>
<b>函数签名:</b>
```go
func IsBlank(str string) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.IsBlank("")
result2 := strutil.IsBlank("\t\v\f\n")
result3 := strutil.IsBlank(" 中文")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// true
// true
// false
}
```
### <span id="HasPrefixAny">HasPrefixAny</span>
<p>检查字符串是否以指定字符串数组中的任何一个开头。</p>
<b>函数签名:</b>
```go
func HasPrefixAny(str string, prefixes []string) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.HasPrefixAny("foo bar", []string{"fo", "xyz", "hello"})
result2 := strutil.HasPrefixAny("foo bar", []string{"oom", "world"})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="HasSuffixAny">HasSuffixAny</span>
<p>检查字符串是否以指定字符串数组中的任何一个结尾。</p>
<b>函数签名:</b>
```go
func HasSuffixAny(str string, suffixes []string) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.HasSuffixAny("foo bar", []string{"bar", "xyz", "hello"})
result2 := strutil.HasSuffixAny("foo bar", []string{"oom", "world"})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
```
### <span id="IndexOffset">IndexOffset</span>
<p>将字符串偏移idxFrom后返回字符串中第一个 substr 实例的索引,如果字符串中不存在 substr则返回 -1。</p>
<b>函数签名:</b>
```go
func IndexOffset(str string, substr string, idxFrom int) int
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
str := "foo bar hello world"
result1 := strutil.IndexOffset(str, "o", 5)
result2 := strutil.IndexOffset(str, "o", 0)
result3 := strutil.IndexOffset(str, "d", len(str)-1)
result4 := strutil.IndexOffset(str, "d", len(str))
result5 := strutil.IndexOffset(str, "f", -1)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// 12
// 1
// 18
// -1
// -1
}
```
### <span id="ReplaceWithMap">ReplaceWithMap</span>
<p>返回`str`的副本以无序的方式被map替换区分大小写。</p>
<b>函数签名:</b>
```go
func ReplaceWithMap(str string, replaces map[string]string) string
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
str := "ac ab ab ac"
replaces := map[string]string{
"a": "1",
"b": "2",
}
result := strutil.ReplaceWithMap(str, replaces)
fmt.Println(result)
// Output:
// 1c 12 12 1c
}
```
### <span id="Trim">Trim</span>
<p>从字符串的开头和结尾去除空格(或其他字符)。 可选参数 characterMask 指定额外的剥离字符。</p>
<b>函数签名:</b>
```go
func Trim(str string, characterMask ...string) string
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
result1 := strutil.Trim("\nabcd")
str := "$ ab cd $ "
result2 := strutil.Trim(str)
result3 := strutil.Trim(str, "$")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// abcd
// $ ab cd $
// ab cd
}
```
### <span id="SplitAndTrim">SplitAndTrim</span>
<p>将字符串str按字符串delimiter拆分为一个切片并对该数组的每个元素调用Trim。忽略Trim后为空的元素。</p>
<b>函数签名:</b>
```go
func SplitAndTrim(str, delimiter string, characterMask ...string) []string
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
str := " a,b, c,d,$1 "
result1 := strutil.SplitAndTrim(str, ",")
result2 := strutil.SplitAndTrim(str, ",", "$")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// [a b c d $1]
// [a b c d 1]
}
```

View File

@@ -239,14 +239,17 @@ func main() {
}
```
### <span id="ExecCommand">CompareOsEnv</span>
### <span id="ExecCommand">ExecCommand</span>
<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>
```go
func ExecCommand(command string) (stdout, stderr string, err error)
type (
Option func(*exec.Cmd)
)
func ExecCommand(command string, opts ...Option) (stdout, stderr string, err error)
```
<b>Example:</b>

View File

@@ -246,7 +246,10 @@ func main() {
<b>Signature:</b>
```go
func ExecCommand(command string) (stdout, stderr string, err error)
type (
Option func(*exec.Cmd)
)
func ExecCommand(command string, opts ...Option) (stdout, stderr string, err error)
```
<b>Example:</b>

View File

@@ -29,6 +29,7 @@ import (
- [IsAlpha](#IsAlpha)
- [IsAllUpper](#IsAllUpper)
- [IsAllLower](#IsAllLower)
- [IsASCII](#IsASCII)
- [IsBase64](#IsBase64)
- [IsChineseMobile](#IsChineseMobile)
- [IsChineseIdNum](#IsChineseIdNum)
@@ -37,11 +38,14 @@ import (
- [IsDns](#IsDns)
- [IsEmail](#IsEmail)
- [IsEmptyString](#IsEmptyString)
- [IsInt](#IsInt)
- [IsFloat](#IsFloat)
- [IsNumber](#IsNumber)
- [IsIntStr](#IsIntStr)
- [IsFloatStr](#IsFloatStr)
- [IsNumberStr](#IsNumberStr)
- [IsJSON](#IsJSON)
- [IsRegexMatch](#IsRegexMatch)
- [IsIntStr](#IsIntStr)
- [IsIp](#IsIp)
- [IsIpV4](#IsIpV4)
- [IsIpV6](#IsIpV6)
@@ -50,6 +54,7 @@ import (
- [IsWeakPassword](#IsWeakPassword)
- [IsZeroValue](#IsZeroValue)
- [IsGBK](#IsGBK)
- [IsPrintable](#IsPrintable)
<div STYLE="page-break-after: always;"></div>
@@ -293,6 +298,46 @@ func main() {
}
```
### <span id="IsASCII">IsASCII</span>
<p>Checks if string is all ASCII char.</p>
<b>Signature:</b>
```go
func IsASCII(str string) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsASCII("ABC")
result2 := validator.IsASCII("123")
result3 := validator.IsASCII("")
result4 := validator.IsASCII("😄")
result5 := validator.IsASCII("你好")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// true
// true
// true
// false
// false
}
```
### <span id="IsBase64">IsBase64</span>
<p>Check if the string is base64 string.</p>
@@ -547,6 +592,154 @@ func main() {
}
```
### <span id="IsInt">IsInt</span>
<p>Check if the value is integer(int, unit) or not.</p>
<b>Signature:</b>
```go
func IsInt(v any) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsInt("")
result2 := validator.IsInt("3")
result3 := validator.IsInt(0.1)
result4 := validator.IsInt(0)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// false
// false
// false
// true
}
```
### <span id="IsFloat">IsFloat</span>
<p>Check if the value is float(float32, float34) or not.</p>
<b>Signature:</b>
```go
func IsFloat(v any) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsFloat("")
result2 := validator.IsFloat("3")
result3 := validator.IsFloat(0)
result4 := validator.IsFloat(0.1)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// false
// false
// false
// true
}
```
### <span id="IsNumber">IsNumber</span>
<p>Check if the value is number(integer, float) or not.</p>
<b>Signature:</b>
```go
func IsNumber(v any) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsNumber("")
result2 := validator.IsNumber("3")
result3 := validator.IsNumber(0.1)
result4 := validator.IsNumber(0)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// false
// false
// true
// true
}
```
### <span id="IsIntStr">IsIntStr</span>
<p>Check if the string can convert to a integer.</p>
<b>Signature:</b>
```go
func IsIntStr(s string) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsIntStr("+3")
result2 := validator.IsIntStr("-3")
result3 := validator.IsIntStr("3.")
result4 := validator.IsIntStr("abc")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// true
// false
// false
}
```
### <span id="IsFloatStr">IsFloatStr</span>
<p>Check if the string can convert to a float.</p>
@@ -642,8 +835,8 @@ import (
func main() {
result1 := validator.IsJSON("{}")
result2 := validator.IsJSON("{\"name\": \"test\"}")
result3 := validator.IsIntStr("")
result4 := validator.IsIntStr("abc")
result3 := validator.IsJSON("")
result4 := validator.IsJSON("abc")
fmt.Println(result1)
fmt.Println(result2)
@@ -689,43 +882,6 @@ func main() {
}
```
### <span id="IsIntStr">IsIntStr</span>
<p>Check if the string can convert to a integer.</p>
<b>Signature:</b>
```go
func IsIntStr(s string) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsIntStr("+3")
result2 := validator.IsIntStr("-3")
result3 := validator.IsIntStr("3.")
result4 := validator.IsIntStr("abc")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// true
// false
// false
}
```
### <span id="IsIp">IsIp</span>
<p>Check if the string is a ip address.</p>
@@ -990,3 +1146,43 @@ func main() {
// true
}
```
### <span id="IsPrintable">IsPrintable</span>
<p>Checks if string is all printable chars.</p>
<b>Signature:</b>
```go
func IsPrintable(str string) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsPrintable("ABC")
result2 := validator.IsPrintable("{id: 123}")
result3 := validator.IsPrintable("")
result4 := validator.IsPrintable("😄")
result5 := validator.IsPrintable("\u0000")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// true
// true
// true
// true
// false
}
```

View File

@@ -29,6 +29,7 @@ import (
- [IsAlpha](#IsAlpha)
- [IsAllUpper](#IsAllUpper)
- [IsAllLower](#IsAllLower)
- [IsASCII](#IsASCII)
- [IsBase64](#IsBase64)
- [IsChineseMobile](#IsChineseMobile)
- [IsChineseIdNum](#IsChineseIdNum)
@@ -37,11 +38,14 @@ import (
- [IsDns](#IsDns)
- [IsEmail](#IsEmail)
- [IsEmptyString](#IsEmptyString)
- [IsInt](#IsInt)
- [IsFloat](#IsFloat)
- [IsNumber](#IsNumber)
- [IsIntStr](#IsIntStr)
- [IsFloatStr](#IsFloatStr)
- [IsNumberStr](#IsNumberStr)
- [IsJSON](#IsJSON)
- [IsRegexMatch](#IsRegexMatch)
- [IsIntStr](#IsIntStr)
- [IsIp](#IsIp)
- [IsIpV4](#IsIpV4)
- [IsIpV6](#IsIpV6)
@@ -50,6 +54,7 @@ import (
- [IsWeakPassword](#IsWeakPassword)
- [IsZeroValue](#IsZeroValue)
- [IsGBK](#IsGBK)
- [IsPrintable](#IsPrintable)
<div STYLE="page-break-after: always;"></div>
@@ -293,6 +298,46 @@ func main() {
}
```
### <span id="IsASCII">IsASCII</span>
<p>验证字符串全部为ASCII字符。</p>
<b>函数签名:</b>
```go
func IsASCII(str string) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsASCII("ABC")
result2 := validator.IsASCII("123")
result3 := validator.IsASCII("")
result4 := validator.IsASCII("😄")
result5 := validator.IsASCII("你好")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// true
// true
// true
// false
// false
}
```
### <span id="IsBase64">IsBase64</span>
<p>验证字符串是否是base64编码</p>
@@ -547,6 +592,155 @@ func main() {
}
```
### <span id="IsInt">IsInt</span>
<p>验证参数是否是整数(int, unit)。</p>
<b>函数签名:</b>
```go
func IsInt(v any) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsInt("")
result2 := validator.IsInt("3")
result3 := validator.IsInt(0.1)
result4 := validator.IsInt(0)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// false
// false
// false
// true
}
```
### <span id="IsFloat">IsFloat</span>
<p>验证参数是否是浮点数((float32, float34)。</p>
<b>函数签名:</b>
```go
func IsFloat(v any) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsFloat("")
result2 := validator.IsFloat("3")
result3 := validator.IsFloat(0)
result4 := validator.IsFloat(0.1)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// false
// false
// false
// true
}
```
### <span id="IsNumber">IsNumber</span>
<p>验证参数是否是数字(integer or float)</p>
<b>函数签名:</b>
```go
func IsNumber(v any) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsNumber("")
result2 := validator.IsNumber("3")
result3 := validator.IsNumber(0.1)
result4 := validator.IsNumber(0)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// false
// false
// true
// true
}
```
### <span id="IsIntStr">IsIntStr</span>
<p>验证字符串是否是可以转换为整数</p>
<b>函数签名:</b>
```go
func IsIntStr(s string) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsIntStr("+3")
result2 := validator.IsIntStr("-3")
result3 := validator.IsIntStr("3.")
result4 := validator.IsIntStr("abc")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// true
// false
// false
}
```
### <span id="IsFloatStr">IsFloatStr</span>
<p>验证字符串是否是可以转换为浮点数</p>
@@ -642,8 +836,8 @@ import (
func main() {
result1 := validator.IsJSON("{}")
result2 := validator.IsJSON("{\"name\": \"test\"}")
result3 := validator.IsIntStr("")
result4 := validator.IsIntStr("abc")
result3 := validator.IsJSON("")
result4 := validator.IsJSON("abc")
fmt.Println(result1)
fmt.Println(result2)
@@ -689,42 +883,7 @@ func main() {
}
```
### <span id="IsIntStr">IsIntStr</span>
<p>验证字符串是否是可以转换为整数</p>
<b>函数签名:</b>
```go
func IsIntStr(s string) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsIntStr("+3")
result2 := validator.IsIntStr("-3")
result3 := validator.IsIntStr("3.")
result4 := validator.IsIntStr("abc")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// true
// false
// false
}
```
### <span id="IsIp">IsIp</span>
@@ -990,3 +1149,44 @@ func main() {
// true
}
```
### <span id="IsPrintable">IsPrintable</span>
<p>检查字符串是否全部为可打印字符。</p>
<b>函数签名:</b>
```go
func IsPrintable(str string) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsPrintable("ABC")
result2 := validator.IsPrintable("{id: 123}")
result3 := validator.IsPrintable("")
result4 := validator.IsPrintable("😄")
result5 := validator.IsPrintable("\u0000")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// true
// true
// true
// true
// false
}
```

View File

@@ -7,6 +7,11 @@ package fileutil
import (
"archive/zip"
"bufio"
"bytes"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/csv"
"errors"
"fmt"
"io"
@@ -15,6 +20,7 @@ import (
"os"
"path"
"path/filepath"
"runtime"
"strings"
)
@@ -67,14 +73,14 @@ func RemoveFile(path string) error {
// CopyFile copy src file to dest file.
// Play: https://go.dev/play/p/Jg9AMJMLrJi
func CopyFile(srcFilePath string, dstFilePath string) error {
srcFile, err := os.Open(srcFilePath)
func CopyFile(srcPath string, dstPath string) error {
srcFile, err := os.Open(srcPath)
if err != nil {
return err
}
defer srcFile.Close()
distFile, err := os.Create(dstFilePath)
distFile, err := os.Create(dstPath)
if err != nil {
return err
}
@@ -173,6 +179,23 @@ func ListFileNames(path string) ([]string, error) {
return result, nil
}
// IsZipFile checks if file is zip or not.
// Play: https://go.dev/play/p/9M0g2j_uF_e
func IsZipFile(filepath string) bool {
f, err := os.Open(filepath)
if err != nil {
return false
}
defer f.Close()
buf := make([]byte, 4)
if n, err := f.Read(buf); err != nil || n < 4 {
return false
}
return bytes.Equal(buf, []byte("PK\x03\x04"))
}
// Zip create zip file, fpath could be a single file or a directory.
// Play: https://go.dev/play/p/j-3sWBp8ik_P
func Zip(fpath string, destPath string) error {
@@ -275,6 +298,7 @@ func UnZip(zipFile string, destPath string) error {
}
}
}
return nil
}
@@ -345,3 +369,87 @@ func MiMeType(file any) string {
}
return mediatype
}
// CurrentPath return current absolute path.
// Play: https://go.dev/play/p/s74a9iBGcSw
func CurrentPath() string {
var absPath string
_, filename, _, ok := runtime.Caller(1)
if ok {
absPath = path.Dir(filename)
}
return absPath
}
// FileSize returns file size in bytes.
// Play: https://go.dev/play/p/H9Z05uD-Jjc
func FileSize(path string) (int64, error) {
f, err := os.Stat(path)
if err != nil {
return 0, err
}
return f.Size(), nil
}
// MTime returns file modified time.
// Play: https://go.dev/play/p/s_Tl7lZoAaY
func MTime(filepath string) (int64, error) {
f, err := os.Stat(filepath)
if err != nil {
return 0, err
}
return f.ModTime().Unix(), nil
}
// MTime returns file sha value, param `shaType` should be 1, 256 or 512.
// Play: https://go.dev/play/p/VfEEcO2MJYf
func Sha(filepath string, shaType ...int) (string, error) {
file, err := os.Open(filepath)
if err != nil {
return "", err
}
defer file.Close()
h := sha1.New()
if len(shaType) > 0 {
if shaType[0] == 1 {
h = sha1.New()
} else if shaType[0] == 256 {
h = sha256.New()
} else if shaType[0] == 512 {
h = sha512.New()
} else {
return "", errors.New("param `shaType` should be 1, 256 or 512.")
}
}
_, err = io.Copy(h, file)
if err != nil {
return "", err
}
sha := fmt.Sprintf("%x", h.Sum(nil))
return sha, nil
}
// ReadCsvFile read file content into slice.
// Play: https://go.dev/play/p/OExTkhGEd3_u
func ReadCsvFile(filepath string) ([][]string, error) {
f, err := os.Open(filepath)
if err != nil {
return nil, err
}
defer f.Close()
csvReader := csv.NewReader(f)
records, err := csvReader.ReadAll()
if err != nil {
return nil, err
}
return records, nil
}

View File

@@ -175,11 +175,11 @@ func ExampleReadFileByLine() {
}
func ExampleListFileNames() {
fileList, _ := ListFileNames("../formatter/")
fileList, _ := ListFileNames("./")
fmt.Println(fileList)
// Output:
// [formatter.go formatter_example_test.go formatter_test.go]
// [file.go file_example_test.go file_test.go]
}
func ExampleZip() {
@@ -223,3 +223,65 @@ func ExampleUnZip() {
// Output:
// application/octet-stream
}
func ExampleIsZipFile() {
result1 := IsZipFile("./file.go")
result2 := IsZipFile("./testdata/file.go.zip")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// false
// true
}
func ExampleFileSize() {
size, err := FileSize("./testdata/test.txt")
fmt.Println(size)
fmt.Println(err)
// Output:
// 20
// <nil>
}
// func ExampleMTime() {
// mtime, err := MTime("./testdata/test.txt")
// fmt.Println(mtime) // 1682478195 (unix timestamp)
// fmt.Println(err)
// // Output:
// // 1682478195
// // <nil>
// }
func ExampleSha() {
sha1, err := Sha("./testdata/test.txt", 1)
sha256, _ := Sha("./testdata/test.txt", 256)
sha512, _ := Sha("./testdata/test.txt", 512)
fmt.Println(sha1)
fmt.Println(sha256)
fmt.Println(sha512)
fmt.Println(err)
// Output:
// dda3cf10c5a6ff6c6659a497bf7261b287af2bc7
// aa6d0a3fbc3442c228d606da09e0c1dc98c69a1cac3da1909199e0266171df35
// d22aba2a1b7a2e2f512756255cc1c3708905646920cb1eb95e45b531ba74774dbbb89baebf1f716220eb9cf4908f1cfc5b2a01267704d9a59f59d77cab609870
// <nil>
}
func ExampleReadCsvFile() {
content, err := ReadCsvFile("./testdata/test.csv")
fmt.Println(content)
fmt.Println(err)
// Output:
// [[Bob 12 male] [Duke 14 male] [Lucy 16 female]]
// <nil>
}

View File

@@ -107,7 +107,7 @@ func TestReadFileToString(t *testing.T) {
_, err := f.WriteString("hello world")
if err != nil {
t.Log(err)
t.Error(err)
}
content, _ := ReadFileToString(path)
@@ -127,7 +127,7 @@ func TestClearFile(t *testing.T) {
_, err := f.WriteString("hello world")
if err != nil {
t.Log(err)
t.Error(err)
}
err = ClearFile(path)
@@ -151,7 +151,7 @@ func TestReadFileByLine(t *testing.T) {
_, err := f.WriteString("hello\nworld")
if err != nil {
t.Log(err)
t.Error(err)
}
expected := []string{"hello", "world"}
@@ -198,9 +198,9 @@ func TestFileMode(t *testing.T) {
CreateFile(srcFile)
mode, err := FileMode(srcFile)
assert.IsNil(err)
t.Log(mode)
assert.IsNotNil(mode)
assert.IsNil(err)
os.Remove(srcFile)
}
@@ -235,9 +235,64 @@ func TestMiMeType(t *testing.T) {
func TestListFileNames(t *testing.T) {
assert := internal.NewAssert(t, "TestListFileNames")
filesInPath, err := ListFileNames("../formatter/")
filesInPath, err := ListFileNames("./")
assert.IsNil(err)
expected := []string{"formatter.go", "formatter_example_test.go", "formatter_test.go"}
expected := []string{"file.go", "file_example_test.go", "file_test.go"}
assert.Equal(expected, filesInPath)
}
func TestCurrentPath(t *testing.T) {
absPath := CurrentPath()
t.Log(absPath)
}
func TestIsZipFile(t *testing.T) {
assert := internal.NewAssert(t, "TestIsZipFile")
assert.Equal(false, IsZipFile("./file.go"))
assert.Equal(true, IsZipFile("./testdata/file.go.zip"))
}
func TestFileSize(t *testing.T) {
assert := internal.NewAssert(t, "TestFileSize")
size, err := FileSize("./testdata/test.txt")
assert.IsNil(err)
assert.Equal(int64(20), size)
}
func TestMTime(t *testing.T) {
assert := internal.NewAssert(t, "TestMTime")
mtime, err := MTime("./testdata/test.txt")
t.Log("TestMTime", mtime)
assert.IsNil(err)
// assert.Equal(int64(1682478195), mtime)
}
func TestSha(t *testing.T) {
assert := internal.NewAssert(t, "TestSha")
sha1, err := Sha("./testdata/test.txt", 1)
sha256, err := Sha("./testdata/test.txt", 256)
sha512, err := Sha("./testdata/test.txt", 512)
assert.IsNil(err)
assert.Equal("dda3cf10c5a6ff6c6659a497bf7261b287af2bc7", sha1)
assert.Equal("aa6d0a3fbc3442c228d606da09e0c1dc98c69a1cac3da1909199e0266171df35", sha256)
assert.Equal("d22aba2a1b7a2e2f512756255cc1c3708905646920cb1eb95e45b531ba74774dbbb89baebf1f716220eb9cf4908f1cfc5b2a01267704d9a59f59d77cab609870", sha512)
}
func TestReadCsvFile(t *testing.T) {
assert := internal.NewAssert(t, "TestReadCsvFile")
content, err := ReadCsvFile("./testdata/test.csv")
assert.IsNil(err)
assert.Equal(3, len(content))
assert.Equal(3, len(content[0]))
assert.Equal("Bob", content[0][0])
}

BIN
fileutil/testdata/file.go.zip vendored Normal file

Binary file not shown.

3
fileutil/testdata/test.csv vendored Normal file
View File

@@ -0,0 +1,3 @@
Bob, 12, male
Duke, 14, male
Lucy, 16, female
1 Bob 12 male
2 Duke 14 male
3 Lucy 16 female

1
fileutil/testdata/test.txt vendored Normal file
View File

@@ -0,0 +1 @@
this is a test file.

178
formatter/byte.go Normal file
View File

@@ -0,0 +1,178 @@
package formatter
import (
"fmt"
"math"
"strconv"
"strings"
"unicode"
)
//
// code logic come from:
// https://github.com/docker/go-units/blob/master/size.go
// http://en.wikipedia.org/wiki/Binary_prefix
const (
// Decimal
UnitB = 1
UnitKB = 1000
UnitMB = 1000 * UnitKB
UnitGB = 1000 * UnitMB
UnitTB = 1000 * UnitGB
UnitPB = 1000 * UnitTB
UnitEB = 1000 * UnitPB
// Binary
UnitBiB = 1
UnitKiB = 1024
UnitMiB = 1024 * UnitKiB
UnitGiB = 1024 * UnitMiB
UnitTiB = 1024 * UnitGiB
UnitPiB = 1024 * UnitTiB
UnitEiB = 1024 * UnitPiB
)
// type byteUnitMap map[byte]int64
var (
decimalByteMap = map[string]uint64{
"b": UnitB,
"kb": UnitKB,
"mb": UnitMB,
"gb": UnitGB,
"tb": UnitTB,
"pb": UnitPB,
"eb": UnitEB,
// Without suffix
"": UnitB,
"k": UnitKB,
"m": UnitMB,
"g": UnitGB,
"t": UnitTB,
"p": UnitPB,
"e": UnitEB,
}
binaryByteMap = map[string]uint64{
"bi": UnitBiB,
"kib": UnitKiB,
"mib": UnitMiB,
"gib": UnitGiB,
"tib": UnitTiB,
"pib": UnitPiB,
"eib": UnitEiB,
// Without suffix
"": UnitBiB,
"ki": UnitKiB,
"mi": UnitMiB,
"gi": UnitGiB,
"ti": UnitTiB,
"pi": UnitPiB,
"ei": UnitEiB,
}
)
var (
decimalByteUnits = []string{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
binaryByteUnits = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
)
// DecimalBytes returns a human readable byte size under decimal standard (base 1000)
// The precision parameter specifies the number of digits after the decimal point, which defaults to 4.
// Play: https://go.dev/play/p/FPXs1suwRcs
func DecimalBytes(size float64, precision ...int) string {
p := 5
if len(precision) > 0 {
p = precision[0] + 1
}
size, unit := calculateByteSize(size, 1000.0, decimalByteUnits)
return fmt.Sprintf("%.*g%s", p, size, unit)
}
// BinaryBytes returns a human-readable byte size under binary standard (base 1024)
// The precision parameter specifies the number of digits after the decimal point, which defaults to 4.
// Play: https://go.dev/play/p/G9oHHMCAZxP
func BinaryBytes(size float64, precision ...int) string {
p := 5
if len(precision) > 0 {
p = precision[0] + 1
}
size, unit := calculateByteSize(size, 1024.0, binaryByteUnits)
return fmt.Sprintf("%.*g%s", p, size, unit)
}
func calculateByteSize(size float64, base float64, byteUnits []string) (float64, string) {
i := 0
unitsLimit := len(byteUnits) - 1
for size >= base && i < unitsLimit {
size = size / base
i++
}
return size, byteUnits[i]
}
// ParseDecimalBytes return the human readable bytes size string into the amount it represents(base 1000).
// ParseDecimalBytes("42 MB") -> 42000000, nil
// Play: https://go.dev/play/p/Am98ybWjvjj
func ParseDecimalBytes(size string) (uint64, error) {
return parseBytes(size, "decimal")
}
// ParseBinaryBytes return the human readable bytes size string into the amount it represents(base 1024).
// ParseBinaryBytes("42 mib") -> 44040192, nil
// Play: https://go.dev/play/p/69v1tTT62x8
func ParseBinaryBytes(size string) (uint64, error) {
return parseBytes(size, "binary")
}
// see https://github.com/dustin/go-humanize/blob/master/bytes.go
func parseBytes(s string, kind string) (uint64, error) {
lastDigit := 0
hasComma := false
for _, r := range s {
if !(unicode.IsDigit(r) || r == '.' || r == ',') {
break
}
if r == ',' {
hasComma = true
}
lastDigit++
}
num := s[:lastDigit]
if hasComma {
num = strings.Replace(num, ",", "", -1)
}
f, err := strconv.ParseFloat(num, 64)
if err != nil {
return 0, err
}
extra := strings.ToLower(strings.TrimSpace(s[lastDigit:]))
if kind == "decimal" {
if m, ok := decimalByteMap[extra]; ok {
f *= float64(m)
if f >= math.MaxUint64 {
return 0, fmt.Errorf("too large: %v", s)
}
return uint64(f), nil
}
} else {
if m, ok := binaryByteMap[extra]; ok {
f *= float64(m)
if f >= math.MaxUint64 {
return 0, fmt.Errorf("too large: %v", s)
}
return uint64(f), nil
}
}
return 0, fmt.Errorf("unhandled size name: %v", extra)
}

87
formatter/byte_test.go Normal file
View File

@@ -0,0 +1,87 @@
package formatter
import (
"testing"
"github.com/duke-git/lancet/v2/internal"
)
func TestDecimalBytes(t *testing.T) {
assert := internal.NewAssert(t, "TestDecimalBytes")
assert.Equal("1KB", DecimalBytes(1000))
assert.Equal("1.024KB", DecimalBytes(1024))
assert.Equal("1.2346MB", DecimalBytes(1234567))
assert.Equal("1.235MB", DecimalBytes(1234567, 3))
assert.Equal("1.123GB", DecimalBytes(float64(1.123*UnitGB)))
assert.Equal("2.123TB", DecimalBytes(float64(2.123*UnitTB)))
assert.Equal("3.123PB", DecimalBytes(float64(3.123*UnitPB)))
assert.Equal("4.123EB", DecimalBytes(float64(4.123*UnitEB)))
assert.Equal("1EB", DecimalBytes(float64(1000*UnitPB)))
}
func TestBinaryBytes(t *testing.T) {
assert := internal.NewAssert(t, "TestBinaryBytes")
assert.Equal("1KiB", BinaryBytes(1024))
assert.Equal("1MiB", BinaryBytes(1024*1024))
assert.Equal("1.1774MiB", BinaryBytes(1234567))
assert.Equal("1.18MiB", BinaryBytes(1234567, 2))
}
func TestParseDecimalBytes(t *testing.T) {
assert := internal.NewAssert(t, "TestParseDecimalBytes")
cases := map[string]uint64{
"12": uint64(12),
"12 k": uint64(12000),
"12 kb": uint64(12000),
"12kb": uint64(12000),
"12k": uint64(12000),
"12K": uint64(12000),
"12KB": uint64(12000),
"12 K": uint64(12000),
"12 KB": uint64(12000),
"12 Kb": uint64(12000),
"12 kB": uint64(12000),
"12.2 KB": uint64(12200),
}
for k, v := range cases {
result, err := ParseDecimalBytes(k)
assert.Equal(v, result)
assert.IsNil(err)
}
_, err := ParseDecimalBytes("12 AB")
assert.IsNotNil(err)
}
func TestParseBinaryBytes(t *testing.T) {
assert := internal.NewAssert(t, "TestParseBinaryBytes")
cases := map[string]uint64{
"12": uint64(12),
"12 ki": uint64(12288),
"12 kib": uint64(12288),
"12kib": uint64(12288),
"12ki": uint64(12288),
"12KI": uint64(12288),
"12KIB": uint64(12288),
"12KiB": uint64(12288),
"12 Ki": uint64(12288),
"12 KiB": uint64(12288),
"12 Kib": uint64(12288),
"12 kiB": uint64(12288),
"12.2 KiB": uint64(12492),
}
for k, v := range cases {
result, err := ParseBinaryBytes(k)
assert.Equal(v, result)
assert.IsNil(err)
}
_, err := ParseDecimalBytes("12 AB")
assert.IsNotNil(err)
}

View File

@@ -5,11 +5,13 @@
package formatter
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"io"
"github.com/duke-git/lancet/v2/convertor"
"github.com/duke-git/lancet/v2/strutil"
"github.com/duke-git/lancet/v2/validator"
"golang.org/x/exp/constraints"
)
@@ -18,54 +20,49 @@ import (
// Comma("12345", "$") => "$12,345", Comma(12345, "$") => "$12,345"
// Play: https://go.dev/play/p/eRD5k2vzUVX
func Comma[T constraints.Float | constraints.Integer | string](value T, symbol string) string {
s, err := numberToString(value)
if err != nil {
if validator.IsInt(value) {
v, err := convertor.ToInt(value)
if err != nil {
return ""
}
return symbol + commaInt(v)
}
if validator.IsFloat(value) {
v, err := convertor.ToFloat(value)
if err != nil {
return ""
}
return symbol + commaFloat(v)
}
if strutil.IsString(value) {
v := fmt.Sprintf("%v", value)
if validator.IsNumberStr(v) {
return symbol + commaStr(v)
}
return ""
}
dotIndex := strings.Index(s, ".")
if dotIndex != -1 {
return symbol + commaString(s[:dotIndex]) + s[dotIndex:]
}
return symbol + commaString(s)
return ""
}
func commaString(s string) string {
if len(s) <= 3 {
return s
}
return commaString(s[:len(s)-3]) + "," + commaString(s[len(s)-3:])
// Pretty data to JSON string.
// Play: https://go.dev/play/p/YsciGj3FH2x
func Pretty(v any) (string, error) {
out, err := json.MarshalIndent(v, "", " ")
return string(out), err
}
func numberToString(value any) (string, error) {
switch reflect.TypeOf(value).Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return fmt.Sprintf("%v", value), nil
// PrettyToWriter pretty encode data to writer.
// Play: https://go.dev/play/p/LPLZ3lDi5ma
func PrettyToWriter(v any, out io.Writer) error {
enc := json.NewEncoder(out)
enc.SetIndent("", " ")
// todo: need to handle 12345678.9 => 1.23456789e+07
case reflect.Float32, reflect.Float64:
return fmt.Sprintf("%v", value), nil
case reflect.String:
{
sv := fmt.Sprintf("%v", value)
if strings.Contains(sv, ".") {
_, err := strconv.ParseFloat(sv, 64)
if err != nil {
return "", err
}
return sv, nil
} else {
_, err := strconv.ParseInt(sv, 10, 64)
if err != nil {
return "", nil
}
return sv, nil
}
}
default:
return "", nil
if err := enc.Encode(v); err != nil {
return err
}
return nil
}

View File

@@ -1,6 +1,9 @@
package formatter
import "fmt"
import (
"bytes"
"fmt"
)
func ExampleComma() {
result1 := Comma("123", "")
@@ -16,3 +19,115 @@ func ExampleComma() {
// $12,345
// ¥1,234,567
}
func ExamplePretty() {
result1, _ := Pretty([]string{"a", "b", "c"})
result2, _ := Pretty(map[string]int{"a": 1})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// [
// "a",
// "b",
// "c"
// ]
// {
// "a": 1
// }
}
func ExamplePrettyToWriter() {
type User struct {
Name string `json:"name"`
Aage uint `json:"age"`
}
user := User{Name: "King", Aage: 10000}
buf := &bytes.Buffer{}
err := PrettyToWriter(user, buf)
fmt.Println(buf)
fmt.Println(err)
// Output:
// {
// "name": "King",
// "age": 10000
// }
//
// <nil>
}
func ExampleDecimalBytes() {
result1 := DecimalBytes(1000)
result2 := DecimalBytes(1024)
result3 := DecimalBytes(1234567)
result4 := DecimalBytes(1234567, 3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 1KB
// 1.024KB
// 1.2346MB
// 1.235MB
}
func ExampleBinaryBytes() {
result1 := BinaryBytes(1024)
result2 := BinaryBytes(1024 * 1024)
result3 := BinaryBytes(1234567)
result4 := BinaryBytes(1234567, 2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 1KiB
// 1MiB
// 1.1774MiB
// 1.18MiB
}
func ExampleParseDecimalBytes() {
result1, _ := ParseDecimalBytes("12")
result2, _ := ParseDecimalBytes("12k")
result3, _ := ParseDecimalBytes("12 Kb")
result4, _ := ParseDecimalBytes("12.2 kb")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 12
// 12000
// 12000
// 12200
}
func ExampleParseBinaryBytes() {
result1, _ := ParseBinaryBytes("12")
result2, _ := ParseBinaryBytes("12ki")
result3, _ := ParseBinaryBytes("12 KiB")
result4, _ := ParseBinaryBytes("12.2 kib")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// 12
// 12288
// 12288
// 12492
}

View File

@@ -0,0 +1,85 @@
package formatter
import (
"bytes"
"math"
"strconv"
"strings"
)
// see https://github.com/dustin/go-humanize/blob/master/comma.go
func commaInt(v int64) string {
sign := ""
// Min int64 can't be negated to a usable value, so it has to be special cased.
if v == math.MinInt64 {
return "-9,223,372,036,854,775,808"
}
if v < 0 {
sign = "-"
v = 0 - v
}
parts := []string{"", "", "", "", "", "", ""}
j := len(parts) - 1
for v > 999 {
parts[j] = strconv.FormatInt(v%1000, 10)
switch len(parts[j]) {
case 2:
parts[j] = "0" + parts[j]
case 1:
parts[j] = "00" + parts[j]
}
v = v / 1000
j--
}
parts[j] = strconv.Itoa(int(v))
return sign + strings.Join(parts[j:], ",")
}
func commaFloat(v float64) string {
buf := &bytes.Buffer{}
if v < 0 {
buf.Write([]byte{'-'})
v = 0 - v
}
comma := []byte{','}
parts := strings.Split(strconv.FormatFloat(v, 'f', -1, 64), ".")
pos := 0
if len(parts[0])%3 != 0 {
pos += len(parts[0]) % 3
buf.WriteString(parts[0][:pos])
buf.Write(comma)
}
for ; pos < len(parts[0]); pos += 3 {
buf.WriteString(parts[0][pos : pos+3])
buf.Write(comma)
}
buf.Truncate(buf.Len() - 1)
if len(parts) > 1 {
buf.Write([]byte{'.'})
buf.WriteString(parts[1])
}
return buf.String()
}
func commaStr(s string) string {
dotIndex := strings.Index(s, ".")
if dotIndex != -1 {
return commaStrRecursive(s[:dotIndex]) + s[dotIndex:]
}
return commaStrRecursive(s)
}
func commaStrRecursive(s string) string {
if len(s) <= 3 {
return s
}
return commaStrRecursive(s[:len(s)-3]) + "," + commaStrRecursive(s[len(s)-3:])
}

View File

@@ -1,6 +1,7 @@
package formatter
import (
"bytes"
"testing"
"github.com/duke-git/lancet/v2/internal"
@@ -16,12 +17,62 @@ func TestComma(t *testing.T) {
assert.Equal("12,345", Comma("12345", ""))
assert.Equal("12,345.6789", Comma("12345.6789", ""))
assert.Equal("123,456,789,000", Comma("123456789000", ""))
assert.Equal("12,345,678.9", Comma("12345678.9", ""))
assert.Equal("12,345", Comma(12345, ""))
assert.Equal("$12,345", Comma(12345, "$"))
assert.Equal("¥12,345", Comma(12345, "¥"))
assert.Equal("12,345.6789", Comma(12345.6789, ""))
assert.Equal("12,345.6789", Comma(+12345.6789, ""))
// assert.Equal("12,345,678.9", Comma(12345678.9, ""))
assert.Equal("12,345,678.9", Comma(12345678.9, ""))
assert.Equal("123,456,789,000", Comma(123456789000, ""))
}
func TestPretty(t *testing.T) {
assert := internal.NewAssert(t, "TestPretty")
cases := []any{
"",
"abc",
123,
[]string{"a", "b", "c"},
map[string]int{"a": 1},
struct {
Abc int `json:"abc"`
}{Abc: 123},
}
expects := []string{
"\"\"",
`"abc"`,
"123",
"[\n \"a\",\n \"b\",\n \"c\"\n]",
"{\n \"a\": 1\n}",
"{\n \"abc\": 123\n}",
}
for i, v := range cases {
result, err := Pretty(v)
assert.IsNil(err)
assert.Equal(expects[i], result)
}
}
func TestPrettyToWriter(t *testing.T) {
assert := internal.NewAssert(t, "TestPrettyToWriter")
type User struct {
Name string `json:"name"`
Aage uint `json:"age"`
}
user := User{Name: "King", Aage: 10000}
expects := "{\n \"name\": \"King\",\n \"age\": 10000\n}\n"
buf := &bytes.Buffer{}
err := PrettyToWriter(user, buf)
assert.IsNil(err)
assert.Equal(expects, buf.String())
}

2
go.mod
View File

@@ -4,5 +4,5 @@ go 1.18
require (
golang.org/x/exp v0.0.0-20221208152030-732eee02a75a
golang.org/x/text v0.5.0
golang.org/x/text v0.9.0
)

2
go.sum
View File

@@ -2,3 +2,5 @@ golang.org/x/exp v0.0.0-20221208152030-732eee02a75a h1:4iLhBPcpqFmylhnkbY3W0ONLU
golang.org/x/exp v0.0.0-20221208152030-732eee02a75a/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
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=
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=

View File

@@ -5,6 +5,7 @@
package internal
import (
"bytes"
"fmt"
"reflect"
"runtime"
@@ -44,6 +45,52 @@ func (a *Assert) NotEqual(expected, actual any) {
}
}
// EqualValues asserts that two objects are equal or convertable to the same types and equal.
// https://github.com/stretchr/testify/assert/assertions.go
func (a *Assert) EqualValues(expected, actual any) {
if !objectsAreEqualValues(expected, actual) {
makeTestFailed(a.T, a.CaseName, expected, actual)
}
}
func objectsAreEqualValues(expected, actual interface{}) bool {
if objectsAreEqual(expected, actual) {
return true
}
actualType := reflect.TypeOf(actual)
if actualType == nil {
return false
}
expectedValue := reflect.ValueOf(expected)
if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
// Attempt comparison after type conversion
return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
}
return false
}
func objectsAreEqual(expected, actual interface{}) bool {
if expected == nil || actual == nil {
return expected == actual
}
exp, ok := expected.([]byte)
if !ok {
return reflect.DeepEqual(expected, actual)
}
act, ok := actual.([]byte)
if !ok {
return false
}
if exp == nil || act == nil {
return exp == nil && act == nil
}
return bytes.Equal(exp, act)
}
// Greater check if expected is greate than actual
func (a *Assert) Greater(expected, actual any) {
if compare(expected, actual) != compareGreater {
@@ -79,16 +126,18 @@ func (a *Assert) LessOrEqual(expected, actual any) {
}
// IsNil check if value is nil
func (a *Assert) IsNil(value any) {
if value != nil {
makeTestFailed(a.T, a.CaseName, nil, value)
func (a *Assert) IsNil(v any) {
if v == nil || (reflect.ValueOf(v).Kind() == reflect.Ptr && reflect.ValueOf(v).IsNil()) {
return
}
makeTestFailed(a.T, a.CaseName, nil, v)
}
// IsNotNil check if value is not nil
func (a *Assert) IsNotNil(value any) {
if value == nil {
makeTestFailed(a.T, a.CaseName, "not nil", value)
func (a *Assert) IsNotNil(v any) {
if v == nil || (reflect.ValueOf(v).Kind() == reflect.Ptr && reflect.ValueOf(v).IsNil()) {
makeTestFailed(a.T, a.CaseName, "not nil", v)
}
}
@@ -162,7 +211,7 @@ func compare(x, y any) int {
}
// logFailedInfo make test failed and log error info
// makeTestFailed make test failed and log error info
func makeTestFailed(t *testing.T, caseName string, expected, actual any) {
_, file, line, _ := runtime.Caller(2)
errInfo := fmt.Sprintf("Case %v failed. file: %v, line: %v, expected: %v, actual: %v.", caseName, file, line, expected, actual)

51
internal/error_join.go Normal file
View File

@@ -0,0 +1,51 @@
package internal
// Note: this file is copyed from the go standart repo (https://github.com/golang/go/blob/master/src/errors/join.go).
// just in order to adapt under go1.9
// do not use it outside lancet lib.
// Join returns an error that wraps the given errors.
// Any nil error values are discarded.
// Join returns nil if errs contains no non-nil values.
// The error formats as the concatenation of the strings obtained
// by calling the Error method of each element of errs, with a newline
// between each string.
func JoinError(errs ...error) error {
n := 0
for _, err := range errs {
if err != nil {
n++
}
}
if n == 0 {
return nil
}
e := &joinError{
errs: make([]error, 0, n),
}
for _, err := range errs {
if err != nil {
e.errs = append(e.errs, err)
}
}
return e
}
type joinError struct {
errs []error
}
func (e *joinError) Error() string {
var b []byte
for i, err := range e.errs {
if i > 0 {
b = append(b, '\n')
}
b = append(b, err.Error()...)
}
return string(b)
}
func (e *joinError) Unwrap() []error {
return e.errs
}

View File

@@ -39,7 +39,7 @@ func Values[K comparable, V any](m map[K]V) []V {
}
// KeysBy creates a slice whose element is the result of function mapper invoked by every map's key.
// Play: todo
// Play: https://go.dev/play/p/hI371iB8Up8
func KeysBy[K comparable, V any, T any](m map[K]V, mapper func(item K) T) []T {
keys := make([]T, 0, len(m))
@@ -51,7 +51,7 @@ func KeysBy[K comparable, V any, T any](m map[K]V, mapper func(item K) T) []T {
}
// ValuesBy creates a slice whose element is the result of function mapper invoked by every map's value.
// Play: todo
// Play: https://go.dev/play/p/sg9-oRidh8f
func ValuesBy[K comparable, V any, T any](m map[K]V, mapper func(item V) T) []T {
keys := make([]T, 0, len(m))
@@ -98,7 +98,7 @@ func Filter[K comparable, V any](m map[K]V, predicate func(key K, value V) bool)
}
// FilterByKeys iterates over map, return a new map whose keys are all given keys.
// Play: todo
// Play: https://go.dev/play/p/7ov6BJHbVqh
func FilterByKeys[K comparable, V any](m map[K]V, keys []K) map[K]V {
result := make(map[K]V)
@@ -111,7 +111,7 @@ func FilterByKeys[K comparable, V any](m map[K]V, keys []K) map[K]V {
}
// FilterByValues iterates over map, return a new map whose values are all given values.
// Play: todo
// Play: https://go.dev/play/p/P3-9MdcXegR
func FilterByValues[K comparable, V comparable](m map[K]V, values []V) map[K]V {
result := make(map[K]V)
@@ -124,7 +124,7 @@ func FilterByValues[K comparable, V comparable](m map[K]V, values []V) map[K]V {
}
// OmitBy is the opposite of Filter, removes all the map elements for which the predicate function returns true.
// Play: todo
// Play: https://go.dev/play/p/YJM4Hj5hNwm
func OmitBy[K comparable, V any](m map[K]V, predicate func(key K, value V) bool) map[K]V {
result := make(map[K]V)
@@ -137,7 +137,7 @@ func OmitBy[K comparable, V any](m map[K]V, predicate func(key K, value V) bool)
}
// OmitByKeys the opposite of FilterByKeys, extracts all the map elements which keys are not omitted.
// Play: todo
// Play: https://go.dev/play/p/jXGrWDBfSRp
func OmitByKeys[K comparable, V any](m map[K]V, keys []K) map[K]V {
result := make(map[K]V)
@@ -150,7 +150,7 @@ func OmitByKeys[K comparable, V any](m map[K]V, keys []K) map[K]V {
}
// OmitByValues the opposite of FilterByValues. remov all elements whose value are in the give slice.
// Play: todo
// Play: https://go.dev/play/p/XB7Y10uw20_U
func OmitByValues[K comparable, V comparable](m map[K]V, values []V) map[K]V {
result := make(map[K]V)
@@ -227,7 +227,7 @@ type Entry[K comparable, V any] struct {
}
// Entries transforms a map into array of key/value pairs.
// Play: todo
// Play: https://go.dev/play/p/Ltb11LNcElY
func Entries[K comparable, V any](m map[K]V) []Entry[K, V] {
entries := make([]Entry[K, V], 0, len(m))
@@ -242,7 +242,7 @@ func Entries[K comparable, V any](m map[K]V) []Entry[K, V] {
}
// FromEntries creates a map based on a slice of key/value pairs
// Play: todo
// Play: https://go.dev/play/p/fTdu4sCNjQO
func FromEntries[K comparable, V any](entries []Entry[K, V]) map[K]V {
result := make(map[K]V, len(entries))
@@ -254,7 +254,7 @@ func FromEntries[K comparable, V any](entries []Entry[K, V]) map[K]V {
}
// Transform a map to another type map.
// Play: todo
// Play: https://go.dev/play/p/P6ovfToM3zj
func Transform[K1 comparable, V1 any, K2 comparable, V2 any](m map[K1]V1, iteratee func(key K1, value V1) (K2, V2)) map[K2]V2 {
result := make(map[K2]V2, len(m))
@@ -267,7 +267,7 @@ func Transform[K1 comparable, V1 any, K2 comparable, V2 any](m map[K1]V1, iterat
}
// MapKeys transforms a map to other type map by manipulating it's keys.
// Play: todo
// Play: https://go.dev/play/p/8scDxWeBDKd
func MapKeys[K comparable, V any, T comparable](m map[K]V, iteratee func(key K, value V) T) map[T]V {
result := make(map[T]V, len(m))
@@ -279,7 +279,7 @@ func MapKeys[K comparable, V any, T comparable](m map[K]V, iteratee func(key K,
}
// MapValues transforms a map to other type map by manipulating it's values.
// Play: todo
// Play: https://go.dev/play/p/g92aY3fc7Iw
func MapValues[K comparable, V any, T any](m map[K]V, iteratee func(key K, value V) T) map[K]T {
result := make(map[K]T, len(m))

View File

@@ -397,3 +397,39 @@ func ExampleOmitByValues() {
// Output:
// map[a:1 b:2 c:3]
}
func ExampleMapTo() {
type (
Person struct {
Name string `json:"name"`
Age int `json:"age"`
Phone string `json:"phone"`
Addr Address `json:"address"`
}
Address struct {
Street string `json:"street"`
Number int `json:"number"`
}
)
personInfo := map[string]interface{}{
"name": "Nothin",
"age": 28,
"phone": "123456789",
"address": map[string]interface{}{
"street": "test",
"number": 1,
},
}
var p Person
err := MapTo(personInfo, &p)
fmt.Println(err)
fmt.Println(p)
// Output:
// <nil>
// {Nothin 28 123456789 {test 1}}
}

181
maputil/typemap.go Normal file
View File

@@ -0,0 +1,181 @@
package maputil
import (
"fmt"
"reflect"
"strings"
)
var mapHandlers = map[reflect.Kind]func(reflect.Value, reflect.Value) error{
reflect.String: convertNormal,
reflect.Int: convertNormal,
reflect.Int16: convertNormal,
reflect.Int32: convertNormal,
reflect.Int64: convertNormal,
reflect.Uint: convertNormal,
reflect.Uint16: convertNormal,
reflect.Uint32: convertNormal,
reflect.Uint64: convertNormal,
reflect.Float32: convertNormal,
reflect.Float64: convertNormal,
reflect.Uint8: convertNormal,
reflect.Int8: convertNormal,
reflect.Struct: convertNormal,
reflect.Complex64: convertNormal,
reflect.Complex128: convertNormal,
}
var _ = func() struct{} {
mapHandlers[reflect.Map] = convertMap
mapHandlers[reflect.Array] = convertSlice
mapHandlers[reflect.Slice] = convertSlice
return struct{}{}
}()
// MapTo try to map any interface to struct or base type
/*
Eg:
v := map[string]interface{}{
"service":map[string]interface{}{
"ip":"127.0.0.1",
"port":1234,
},
version:"v1.0.01"
}
type Target struct {
Service struct {
Ip string `json:"ip"`
Port int `json:"port"`
} `json:"service"`
Ver string `json:"version"`
}
var dist Target
if err := maputil.MapTo(v,&dist); err != nil {
log.Println(err)
return
}
log.Println(dist)
*/
// Play: https://go.dev/play/p/4K7KBEPgS5M
func MapTo(src any, dst any) error {
dstRef := reflect.ValueOf(dst)
if dstRef.Kind() != reflect.Ptr {
return fmt.Errorf("dst is not ptr")
}
dstRef = reflect.Indirect(dstRef)
srcRef := reflect.ValueOf(src)
if srcRef.Kind() == reflect.Ptr || srcRef.Kind() == reflect.Interface {
srcRef = srcRef.Elem()
}
if f, ok := mapHandlers[srcRef.Kind()]; ok {
return f(srcRef, dstRef)
}
return fmt.Errorf("no implemented:%s", srcRef.Type())
}
func convertNormal(src reflect.Value, dst reflect.Value) error {
if dst.CanSet() {
if src.Type() == dst.Type() {
dst.Set(src)
} else if src.CanConvert(dst.Type()) {
dst.Set(src.Convert(dst.Type()))
} else {
return fmt.Errorf("can not convert:%s:%s", src.Type().String(), dst.Type().String())
}
}
return nil
}
func convertSlice(src reflect.Value, dst reflect.Value) error {
if dst.Kind() != reflect.Array && dst.Kind() != reflect.Slice {
return fmt.Errorf("error type:%s", dst.Type().String())
}
l := src.Len()
target := reflect.MakeSlice(dst.Type(), l, l)
if dst.CanSet() {
dst.Set(target)
}
for i := 0; i < l; i++ {
srcValue := src.Index(i)
if srcValue.Kind() == reflect.Ptr || srcValue.Kind() == reflect.Interface {
srcValue = srcValue.Elem()
}
if f, ok := mapHandlers[srcValue.Kind()]; ok {
err := f(srcValue, dst.Index(i))
if err != nil {
return err
}
}
}
return nil
}
func convertMap(src reflect.Value, dst reflect.Value) error {
if src.Kind() != reflect.Map || dst.Kind() != reflect.Struct {
if src.Kind() == reflect.Interface {
return convertMap(src.Elem(), dst)
} else {
return fmt.Errorf("src or dst type error,%s,%s", src.Type().String(), dst.Type().String())
}
}
dstType := dst.Type()
num := dstType.NumField()
exist := map[string]int{}
for i := 0; i < num; i++ {
k := dstType.Field(i).Tag.Get("json")
if k == "" {
k = dstType.Field(i).Name
}
if strings.Contains(k, ",") {
taglist := strings.Split(k, ",")
if taglist[0] == "" {
k = dstType.Field(i).Name
} else {
k = taglist[0]
}
}
exist[k] = i
}
keys := src.MapKeys()
for _, key := range keys {
if index, ok := exist[key.String()]; ok {
v := dst.Field(index)
if v.Kind() == reflect.Struct {
err := convertMap(src.MapIndex(key), v)
if err != nil {
return err
}
} else {
if v.CanSet() {
if v.Type() == src.MapIndex(key).Elem().Type() {
v.Set(src.MapIndex(key).Elem())
} else if src.MapIndex(key).Elem().CanConvert(v.Type()) {
v.Set(src.MapIndex(key).Elem().Convert(v.Type()))
} else if f, ok := mapHandlers[src.MapIndex(key).Elem().Kind()]; ok && f != nil {
err := f(src.MapIndex(key).Elem(), v)
if err != nil {
return err
}
} else {
return fmt.Errorf("error type:d(%s)s(%s)", v.Type(), src.Type())
}
}
}
}
}
return nil
}

111
maputil/typemap_test.go Normal file
View File

@@ -0,0 +1,111 @@
package maputil
import (
"testing"
"github.com/duke-git/lancet/v2/internal"
)
type (
Person struct {
Name string `json:"name"`
Age int `json:"age"`
Phone string `json:"phone"`
Addr Address `json:"address"`
}
Address struct {
Street string `json:"street"`
Number int `json:"number"`
}
)
func TestStructType(t *testing.T) {
assert := internal.NewAssert(t, "TestStructType")
src := map[string]interface{}{
"name": "Nothin",
"age": 28,
"phone": "123456789",
"address": map[string]interface{}{
"street": "test",
"number": 1,
},
}
var p Person
err := MapTo(src, &p)
assert.IsNil(err)
assert.Equal(src["name"], p.Name)
assert.Equal(src["age"], p.Age)
assert.Equal(src["phone"], p.Phone)
assert.Equal("test", p.Addr.Street)
assert.Equal(1, p.Addr.Number)
}
func TestBaseType(t *testing.T) {
assert := internal.NewAssert(t, "TestBaseType")
tc := map[string]interface{}{
"i32": -32,
"i8": -8,
"i16": -16,
"i64": -64,
"i": -1,
"u32": 32,
"u8": 8,
"u16": 16,
"u64": 64,
"u": 1,
"tf": true,
"f32": 1.32,
"f64": 1.64,
"str": "hello mapto",
"complex": 1 + 3i,
}
type BaseType struct {
I int `json:"i"`
I8 int8 `json:"i8"`
I16 int16 `json:"i16"`
I32 int32 `json:"i32"`
I64 int64 `json:"i64"`
U uint `json:"u"`
U8 uint8 `json:"u8"`
U16 uint16 `json:"u16"`
U32 uint32 `json:"u32"`
U64 uint64 `json:"u64"`
F32 float32 `json:"f32"`
F64 float64 `json:"f64"`
Tf bool `json:"tf"`
Str string `json:"str"`
Comp complex128 `json:"complex"`
}
var dist BaseType
err := MapTo(tc, &dist)
assert.IsNil(err)
var number float64
MapTo(tc["i"], &number)
assert.EqualValues(-1, number)
MapTo(tc["i8"], &number)
assert.EqualValues(-8, number)
MapTo(tc["i16"], &number)
assert.EqualValues(-16, number)
MapTo(tc["i32"], &number)
assert.EqualValues(-32, number)
MapTo(tc["i64"], &number)
assert.EqualValues(-64, number)
MapTo(tc["u"], &number)
assert.EqualValues(1, number)
MapTo(tc["u8"], &number)
assert.EqualValues(8, number)
MapTo(tc["u16"], &number)
assert.EqualValues(16, number)
MapTo(tc["u32"], &number)
assert.EqualValues(32, number)
MapTo(tc["u64"], &number)
assert.EqualValues(64, number)
}

View File

@@ -60,7 +60,7 @@ func Percent(val, total float64, n int) float64 {
if total == 0 {
return float64(0)
}
tmp := val / total
tmp := val / total * 100
result := RoundToFloat(tmp, n)
return result
@@ -183,3 +183,121 @@ func Average[T constraints.Integer | constraints.Float](numbers ...T) T {
}
return sum / n
}
// Range creates a slice of numbers from start with specified count, element step is 1.
// Play: https://go.dev/play/p/9ke2opxa8ZP
func Range[T constraints.Integer | constraints.Float](start T, count int) []T {
size := count
if count < 0 {
size = -count
}
result := make([]T, size)
for i, j := 0, start; i < size; i, j = i+1, j+1 {
result[i] = j
}
return result
}
// RangeWithStep creates a slice of numbers from start to end with specified step.
// Play: https://go.dev/play/p/akLWz0EqOSM
func RangeWithStep[T constraints.Integer | constraints.Float](start, end, step T) []T {
result := []T{}
if start >= end || step == 0 {
return result
}
for i := start; i < end; i += step {
result = append(result, i)
}
return result
}
// AngleToRadian converts angle value to radian value.
// Play: https://go.dev/play/p/CIvlICqrHql
func AngleToRadian(angle float64) float64 {
radian := angle * (math.Pi / 180)
return radian
}
// RadianToAngle converts radian value to angle value.
// Play: https://go.dev/play/p/dQtmOTUOMgi
func RadianToAngle(radian float64) float64 {
angle := radian * (180 / math.Pi)
return angle
}
// PointDistance get two points distance.
// Play: https://go.dev/play/p/RrG4JIaziM8
func PointDistance(x1, y1, x2, y2 float64) float64 {
a := x1 - x2
b := y1 - y2
c := math.Pow(a, 2) + math.Pow(b, 2)
return math.Sqrt(c)
}
// IsPrimes checks if number is prime number.
// Play: https://go.dev/play/p/Rdd8UTHZJ7u
func IsPrime(n int) bool {
if n < 2 {
return false
}
for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
if n%i == 0 {
return false
}
}
return true
}
// GCD return greatest common divisor (GCD) of integers.
// Play: todo
func GCD[T constraints.Integer](integers ...T) T {
result := integers[0]
for k := range integers {
result = gcd(integers[k], result)
if result == 1 {
return 1
}
}
return result
}
// find greatest common divisor (GCD)
func gcd[T constraints.Integer](a, b T) T {
if b == 0 {
return a
}
return gcd(b, a%b)
}
// LCM return Least Common Multiple (LCM) of integers.
// Play: todo
func LCM[T constraints.Integer](integers ...T) T {
result := integers[0]
for k := range integers {
result = lcm(integers[k], result)
}
return result
}
// find Least Common Multiple (LCM) via GCD.
func lcm[T constraints.Integer](a, b T) T {
if a == 0 || b == 0 {
panic("lcm function: provide non zero integers only.")
}
return a * b / gcd(a, b)
}

View File

@@ -1,6 +1,9 @@
package mathutil
import "fmt"
import (
"fmt"
"math"
)
func ExampleExponent() {
result1 := Exponent(10, 0)
@@ -50,13 +53,16 @@ func ExampleFactorial() {
func ExamplePercent() {
result1 := Percent(1, 2, 2)
result2 := Percent(0.1, 0.3, 2)
result3 := Percent(-30305, 408420, 2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.5
// 0.33
// 50
// 33.33
// -7.42
}
func ExampleRoundToFloat() {
@@ -185,3 +191,132 @@ func ExampleMinBy() {
// ab
//
}
func ExampleRange() {
result1 := Range(1, 4)
result2 := Range(1, -4)
result3 := Range(-4, 4)
result4 := Range(1.0, 4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// [1 2 3 4]
// [1 2 3 4]
// [-4 -3 -2 -1]
// [1 2 3 4]
}
func ExampleRangeWithStep() {
result1 := RangeWithStep(1, 4, 1)
result2 := RangeWithStep(1, -1, 0)
result3 := RangeWithStep(-4, 1, 2)
result4 := RangeWithStep(1.0, 4.0, 1.1)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// [1 2 3]
// []
// [-4 -2 0]
// [1 2.1 3.2]
}
func ExampleAngleToRadian() {
result1 := AngleToRadian(45)
result2 := AngleToRadian(90)
result3 := AngleToRadian(180)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.7853981633974483
// 1.5707963267948966
// 3.141592653589793
}
func ExampleRadianToAngle() {
result1 := RadianToAngle(math.Pi)
result2 := RadianToAngle(math.Pi / 2)
result3 := RadianToAngle(math.Pi / 4)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 180
// 90
// 45
}
func ExamplePointDistance() {
result1 := PointDistance(1, 1, 4, 5)
fmt.Println(result1)
// Output:
// 5
}
func ExampleIsPrime() {
result1 := IsPrime(-1)
result2 := IsPrime(0)
result3 := IsPrime(1)
result4 := IsPrime(2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// false
// false
// false
// true
}
func ExampleGCD() {
result1 := GCD(1, 1)
result2 := GCD(1, -1)
result3 := GCD(-1, 1)
result4 := GCD(-1, -1)
result5 := GCD(3, 6, 9)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// 1
// 1
// -1
// -1
// 3
}
func ExampleLCM() {
result1 := LCM(1, 1)
result2 := LCM(1, 2)
result3 := LCM(3, 6, 9)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 1
// 2
// 18
}

View File

@@ -1,6 +1,7 @@
package mathutil
import (
"math"
"testing"
"github.com/duke-git/lancet/v2/internal"
@@ -35,8 +36,9 @@ func TestFactorial(t *testing.T) {
func TestPercent(t *testing.T) {
assert := internal.NewAssert(t, "TestPercent")
assert.Equal(0.5, Percent(1, 2, 2))
assert.Equal(0.33, Percent(0.1, 0.3, 2))
assert.EqualValues(50, Percent(1, 2, 2))
assert.EqualValues(33.33, Percent(0.1, 0.3, 2))
assert.EqualValues(-7.42, Percent(-30305, 408420, 2))
}
func TestRoundToFloat(t *testing.T) {
@@ -77,7 +79,6 @@ func TestAverage(t *testing.T) {
assert.Equal(Average(0, 0), 0)
assert.Equal(Average(1, 1), 1)
avg := Average(1.2, 1.4)
t.Log(avg)
assert.Equal(1.3, RoundToFloat(avg, 1))
}
@@ -137,3 +138,114 @@ func TestMinBy(t *testing.T) {
})
assert.Equal("", res3)
}
func TestRange(t *testing.T) {
assert := internal.NewAssert(t, "TestRange")
result1 := Range(1, 4)
result2 := Range(1, -4)
result3 := Range(-4, 4)
result4 := Range(1.0, 4)
result5 := Range(1, 0)
assert.Equal([]int{1, 2, 3, 4}, result1)
assert.Equal([]int{1, 2, 3, 4}, result2)
assert.Equal([]int{-4, -3, -2, -1}, result3)
assert.Equal([]float64{1.0, 2.0, 3.0, 4.0}, result4)
assert.Equal([]int{}, result5)
}
func TestRangeWithStep(t *testing.T) {
assert := internal.NewAssert(t, "TestRangeWithStep")
result1 := RangeWithStep(1, 4, 1)
result2 := RangeWithStep(1, -1, 0)
result3 := RangeWithStep(-4, 1, 2)
result4 := RangeWithStep(1.0, 4.0, 1.1)
assert.Equal([]int{1, 2, 3}, result1)
assert.Equal([]int{}, result2)
assert.Equal([]int{-4, -2, 0}, result3)
assert.Equal([]float64{1.0, 2.1, 3.2}, result4)
}
func TestAngleToRadian(t *testing.T) {
assert := internal.NewAssert(t, "TestAngleToRadian")
result1 := AngleToRadian(45)
result2 := AngleToRadian(90)
result3 := AngleToRadian(180)
assert.Equal(0.7853981633974483, result1)
assert.Equal(1.5707963267948966, result2)
assert.Equal(3.141592653589793, result3)
}
func TestRadianToAngle(t *testing.T) {
assert := internal.NewAssert(t, "TestAngleToRadian")
result1 := RadianToAngle(math.Pi)
result2 := RadianToAngle(math.Pi / 2)
result3 := RadianToAngle(math.Pi / 4)
assert.Equal(float64(180), result1)
assert.Equal(float64(90), result2)
assert.Equal(float64(45), result3)
}
func TestPointDistance(t *testing.T) {
assert := internal.NewAssert(t, "TestPointDistance")
result1 := PointDistance(1, 1, 4, 5)
assert.Equal(float64(5), result1)
}
func TestIsPrime(t *testing.T) {
assert := internal.NewAssert(t, "TestIsPrime")
assert.Equal(false, IsPrime(-1))
assert.Equal(false, IsPrime(0))
assert.Equal(false, IsPrime(1))
assert.Equal(true, IsPrime(2))
assert.Equal(true, IsPrime(3))
assert.Equal(false, IsPrime(4))
}
func TestGCD(t *testing.T) {
assert := internal.NewAssert(t, "TestGCD")
assert.Equal(1, GCD(1, 1))
assert.Equal(1, GCD(1, -1))
assert.Equal(-1, GCD(-1, 1))
assert.Equal(-1, GCD(-1, -1))
assert.Equal(1, GCD(1, 0))
assert.Equal(1, GCD(0, 1))
assert.Equal(-1, GCD(-1, 0))
assert.Equal(-1, GCD(0, -1))
assert.Equal(1, GCD(1, -2))
assert.Equal(1, GCD(-2, 1))
assert.Equal(-1, GCD(-1, 2))
assert.Equal(-1, GCD(2, -1))
assert.Equal(-1, GCD(-1, -2))
assert.Equal(-1, GCD(-2, -1))
assert.Equal(-9, GCD(-27, -36))
assert.Equal(3, GCD(3, 6, 9))
}
func TestLCM(t *testing.T) {
assert := internal.NewAssert(t, "TestLCM")
assert.Equal(1, LCM(1))
assert.Equal(-1, LCM(-1))
assert.Equal(-1, LCM(1, -1))
assert.Equal(1, LCM(-1, 1))
assert.Equal(1, LCM(1, 1))
assert.Equal(-1, LCM(-1, -1))
assert.Equal(2, LCM(1, 2))
assert.Equal(18, LCM(3, 6, 9))
}

View File

@@ -21,12 +21,11 @@ import (
"io"
"net/http"
"net/url"
"reflect"
"regexp"
"sort"
"strings"
"time"
"github.com/duke-git/lancet/v2/convertor"
"github.com/duke-git/lancet/v2/slice"
)
@@ -219,7 +218,7 @@ func (client *HttpClient) setTLS(rawUrl string) {
}
}
// setHeader set http rquest header
// setHeader set http request header
func (client *HttpClient) setHeader(req *http.Request, headers http.Header) {
if headers == nil {
headers = make(http.Header)
@@ -278,29 +277,15 @@ func validateRequest(req *HttpRequest) error {
// StructToUrlValues convert struct to url valuse,
// only convert the field which is exported and has `json` tag.
// Play: https://go.dev/play/p/pFqMkM40w9z
func StructToUrlValues(targetStruct any) url.Values {
rv := reflect.ValueOf(targetStruct)
rt := reflect.TypeOf(targetStruct)
if rt.Kind() == reflect.Ptr {
rt = rt.Elem()
}
if rt.Kind() != reflect.Struct {
panic(fmt.Errorf("data type %T not support, shuld be struct or pointer to struct", targetStruct))
}
func StructToUrlValues(targetStruct any) (url.Values, error) {
result := url.Values{}
fieldNum := rt.NumField()
pattern := `^[A-Z]`
regex := regexp.MustCompile(pattern)
for i := 0; i < fieldNum; i++ {
name := rt.Field(i).Name
tag := rt.Field(i).Tag.Get("json")
if regex.MatchString(name) && tag != "" {
result.Add(tag, fmt.Sprintf("%v", rv.Field(i).Interface()))
}
s, err := convertor.StructToMap(targetStruct)
if err != nil {
return nil, err
}
for k, v := range s {
result.Add(k, fmt.Sprintf("%v", v))
}
return result
return result, nil
}

View File

@@ -182,7 +182,7 @@ func TestHttpClient_Get(t *testing.T) {
var todo Todo
err = httpClient.DecodeResponse(resp, &todo)
if err != nil {
t.Log(err)
t.FailNow()
}
assert.Equal(1, todo.Id)
@@ -217,30 +217,31 @@ func TestStructToUrlValues(t *testing.T) {
assert := internal.NewAssert(t, "TestStructToUrlValues")
type TodoQuery struct {
Id int `json:"id"`
UserId int `json:"userId"`
Id int `json:"id"`
UserId int `json:"userId"`
Name string `json:"name,omitempty"`
}
todoQuery := TodoQuery{
item1 := TodoQuery{
Id: 1,
UserId: 1,
UserId: 123,
Name: "",
}
todoValues, err := StructToUrlValues(item1)
if err != nil {
t.Errorf("params is invalid: %v", err)
}
todoValues := StructToUrlValues(todoQuery)
assert.Equal("1", todoValues.Get("id"))
assert.Equal("1", todoValues.Get("userId"))
assert.Equal("123", todoValues.Get("userId"))
assert.Equal("", todoValues.Get("name"))
request := &HttpRequest{
RawURL: "https://jsonplaceholder.typicode.com/todos",
Method: "GET",
QueryParams: todoValues,
item2 := TodoQuery{
Id: 2,
UserId: 456,
}
queryValues2, _ := StructToUrlValues(item2)
httpClient := NewHttpClient()
resp, err := httpClient.SendRequest(request)
if err != nil || resp.StatusCode != 200 {
log.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
t.Log("response: ", string(body))
assert.Equal("2", queryValues2.Get("id"))
assert.Equal("456", queryValues2.Get("userId"))
assert.Equal("", queryValues2.Get("name"))
}

View File

@@ -1,12 +1,21 @@
package netutil
import (
"bytes"
"encoding/json"
"errors"
"io"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"runtime"
"strings"
"time"
"github.com/duke-git/lancet/v2/fileutil"
)
// GetInternalIp return internal ipv4.
@@ -178,3 +187,95 @@ func EncodeUrl(urlStr string) (string, error) {
return URL.String(), nil
}
// DownloadFile will upload the file to a server.
func UploadFile(filepath string, server string) (bool, error) {
if !fileutil.IsExist(filepath) {
return false, errors.New("file not exist")
}
fileInfo, err := os.Stat(filepath)
if err != nil {
return false, err
}
bodyBuffer := &bytes.Buffer{}
writer := multipart.NewWriter(bodyBuffer)
formFile, err := writer.CreateFormFile("uploadfile", fileInfo.Name())
if err != nil {
return false, err
}
srcFile, err := os.Open(filepath)
if err != nil {
return false, err
}
defer srcFile.Close()
_, err = io.Copy(formFile, srcFile)
if err != nil {
return false, err
}
contentType := writer.FormDataContentType()
writer.Close()
_, err = http.Post(server, contentType, bodyBuffer)
if err != nil {
return false, err
}
return true, nil
}
// DownloadFile will download the file exist in url to a local file.
// Play: todo
func DownloadFile(filepath string, url string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return err
}
// IsPingConnected checks if can ping specified host or not.
// Play: https://go.dev/play/p/q8OzTijsA87
func IsPingConnected(host string) bool {
cmd := exec.Command("ping", host, "-c", "4", "-W", "6")
if runtime.GOOS == "windows" {
cmd = exec.Command("ping", host, "-n", "4", "-w", "6")
}
err := cmd.Run()
if err != nil {
return false
}
return true
}
// IsTelnetConnected checks if can telnet specified host or not.
// Play: https://go.dev/play/p/yiLCGtQv_ZG
func IsTelnetConnected(host string, port string) bool {
adder := host + ":" + port
conn, err := net.DialTimeout("tcp", adder, 5*time.Second)
if err != nil {
return false
}
defer conn.Close()
return true
}

View File

@@ -16,18 +16,18 @@ func ExampleGetInternalIp() {
// true
}
func ExampleGetPublicIpInfo() {
ipInfo, err := GetPublicIpInfo()
if err != nil {
return
}
// func ExampleGetPublicIpInfo() {
// ipInfo, err := GetPublicIpInfo()
// if err != nil {
// return
// }
result := IsPublicIP(net.ParseIP(ipInfo.Ip))
fmt.Println(result)
// result := IsPublicIP(net.ParseIP(ipInfo.Ip))
// fmt.Println(result)
// Output:
// true
}
// // Output:
// // true
// }
func ExampleGetRequestPublicIp() {
ip := "36.112.24.10"
@@ -123,21 +123,45 @@ func ExampleHttpClient_DecodeResponse() {
func ExampleStructToUrlValues() {
type TodoQuery struct {
Id int `json:"id"`
Name string `json:"name"`
Id int `json:"id"`
UserId int `json:"userId"`
Name string `json:"name,omitempty"`
Status string
}
todoQuery := TodoQuery{
Id: 1,
Name: "Test",
item1 := TodoQuery{
Id: 1,
UserId: 123,
Name: "test",
Status: "completed",
}
queryValues1, err := StructToUrlValues(item1)
if err != nil {
return
}
todoValues := StructToUrlValues(todoQuery)
fmt.Println(todoValues.Get("id"))
fmt.Println(todoValues.Get("name"))
item2 := TodoQuery{
Id: 2,
UserId: 456,
}
queryValues2, _ := StructToUrlValues(item2)
fmt.Println(queryValues1.Get("id"))
fmt.Println(queryValues1.Get("userId"))
fmt.Println(queryValues1.Get("name"))
fmt.Println(queryValues1.Get("status"))
fmt.Println(queryValues2.Get("id"))
fmt.Println(queryValues2.Get("userId"))
fmt.Println(queryValues2.Get("name"))
// Output:
// 1
// Test
// 123
// test
//
// 2
// 456
//
}
func ExampleConvertMapToQueryString() {
@@ -154,3 +178,26 @@ func ExampleConvertMapToQueryString() {
// Output:
// a=1&b=2&c=3
}
func ExampleIsPingConnected() {
// result1 := IsPingConnected("bing.com")
result2 := IsPingConnected("www.!@#&&&.com")
// fmt.Println(result1)
fmt.Println(result2)
// Output:
// false
}
func ExampleIsTelnetConnected() {
result1 := IsTelnetConnected("bing.com", "80")
result2 := IsTelnetConnected("www.baidu.com", "123")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}

View File

@@ -40,14 +40,14 @@ func TestGetRequestPublicIp(t *testing.T) {
assert.Equal(publicIp, ip)
}
func TestGetPublicIpInfo(t *testing.T) {
assert := internal.NewAssert(t, "TestGetPublicIpInfo")
// func TestGetPublicIpInfo(t *testing.T) {
// assert := internal.NewAssert(t, "TestGetPublicIpInfo")
publicIpInfo, err := GetPublicIpInfo()
assert.IsNil(err)
// publicIpInfo, err := GetPublicIpInfo()
// assert.IsNil(err)
t.Logf("public ip info is: %+v \n", *publicIpInfo)
}
// t.Logf("public ip info is: %+v \n", *publicIpInfo)
// }
func TestIsPublicIP(t *testing.T) {
assert := internal.NewAssert(t, "TestIsPublicIP")
@@ -98,14 +98,42 @@ func TestGetMacAddrs(t *testing.T) {
}
func TestEncodeUrl(t *testing.T) {
assert := internal.NewAssert(t, "TestIsInternalIP")
assert := internal.NewAssert(t, "TestEncodeUrl")
urlAddr := "http://www.lancet.com?a=1&b=[2]"
encodedUrl, err := EncodeUrl(urlAddr)
if err != nil {
t.Log(err)
t.Fail()
}
expected := "http://www.lancet.com?a=1&b=%5B2%5D"
assert.Equal(expected, encodedUrl)
}
// func TestDownloadFile(t *testing.T) {
// assert := internal.NewAssert(t, "TestDownloadFile")
// err := DownloadFile("./lancet_logo.jpg", "https://picx.zhimg.com/v2-fc82a4199749de9cfb71e32e54f489d3_720w.jpg?source=172ae18b")
// assert.IsNil(err)
// }
func TestIsPingConnected(t *testing.T) {
assert := internal.NewAssert(t, "TestIsPingConnected")
// in github action env, this will fail
// result1 := IsPingConnected("www.baidu.com")
// assert.Equal(true, result1)
result2 := IsPingConnected("www.!@#&&&.com")
assert.Equal(false, result2)
}
func TestTelnetConnected(t *testing.T) {
assert := internal.NewAssert(t, "TestTelnetConnected")
result1 := IsTelnetConnected("bing.com", "80")
assert.Equal(true, result1)
result2 := IsTelnetConnected("www.baidu.com", "123")
assert.Equal(false, result2)
}

14
pointer/pointer.go Normal file
View File

@@ -0,0 +1,14 @@
package pointer
import "reflect"
// ExtractPointer returns the underlying value by the given interface type
func ExtractPointer(value any) any {
t := reflect.TypeOf(value)
v := reflect.ValueOf(value)
if t.Kind() != reflect.Pointer {
return value
}
return ExtractPointer(v.Elem().Interface())
}

18
pointer/pointer_test.go Normal file
View File

@@ -0,0 +1,18 @@
package pointer
import (
"github.com/duke-git/lancet/v2/internal"
"testing"
)
func TestExtractPointer(t *testing.T) {
assert := internal.NewAssert(t, "TestExtractPointer")
a := 1
b := &a
c := &b
d := &c
assert.Equal(1, ExtractPointer(d))
}

279
promise/promise.go Normal file
View File

@@ -0,0 +1,279 @@
// Copyright 2023 dudaodong@gmail.com. All rights reserved.
// Use of this source code is governed by MIT license
// Package promise contains some functions to support async programming.
package promise
import (
"errors"
"fmt"
"sync"
"github.com/duke-git/lancet/v2/internal"
)
// Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
// ref : chebyrash/promise (https://github.com/chebyrash/promise)
// see js promise: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
type Promise[T any] struct {
runnable func(resolve func(T), reject func(error))
result T
err error
pending bool
mu *sync.Mutex
wg *sync.WaitGroup
}
// New create a new promise instance.
func New[T any](runnable func(resolve func(T), reject func(error))) *Promise[T] {
if runnable == nil {
panic("runnable function should not be nil")
}
p := &Promise[T]{
runnable: runnable,
pending: true,
mu: &sync.Mutex{},
wg: &sync.WaitGroup{},
}
defer p.run()
return p
}
func (p *Promise[T]) run() {
p.wg.Add(1)
go func() {
defer func() {
if !p.pending {
return
}
if err := recover(); err != nil {
p.reject(errors.New(fmt.Sprint(err)))
}
}()
p.runnable(p.resolve, p.reject)
}()
}
// Resolve returns a Promise that has been resolved with a given value.
func Resolve[T any](resolution T) *Promise[T] {
return &Promise[T]{
result: resolution,
pending: false,
mu: &sync.Mutex{},
wg: &sync.WaitGroup{},
}
}
func (p *Promise[T]) resolve(value T) {
p.mu.Lock()
defer p.mu.Unlock()
if !p.pending {
return
}
p.result = value
p.pending = false
p.wg.Done()
}
// Reject returns a Promise that has been rejected with a given error.
func Reject[T any](err error) *Promise[T] {
return &Promise[T]{
err: err,
pending: false,
mu: &sync.Mutex{},
wg: &sync.WaitGroup{},
}
}
func (p *Promise[T]) reject(err error) {
p.mu.Lock()
defer p.mu.Unlock()
if !p.pending {
return
}
p.err = err
p.pending = false
p.wg.Done()
}
// Then allows chain calls to other promise methods.
func Then[T1, T2 any](promise *Promise[T1], resolve1 func(value T1) T2) *Promise[T2] {
return New(func(resolve2 func(T2), reject func(error)) {
result, err := promise.Await()
if err != nil {
reject(err)
return
}
resolve2(resolve1(result))
})
}
// Then allows chain calls to other promise methods.
func (p *Promise[T]) Then(resolve func(value T) T) *Promise[T] {
return New(func(_resolve func(T), reject func(error)) {
result, err := p.Await()
if err != nil {
reject(err)
return
}
_resolve(resolve(result))
})
}
// Catch allows to chain promises.
func Catch[T any](promise *Promise[T], rejection func(err error) error) *Promise[T] {
return New(func(resolve func(T), reject func(error)) {
result, err := promise.Await()
if err != nil {
reject(rejection(err))
return
}
resolve(result)
})
}
// Catch chain an existing promise with an intermediate reject function.
func (p *Promise[T]) Catch(reject func(error) error) *Promise[T] {
return New(func(resolve func(T), rej func(error)) {
resutl, err := p.Await()
if err != nil {
rej(reject(err))
return
}
resolve(resutl)
})
}
// Await blocks until the 'runable' to finish execution.
func (p *Promise[T]) Await() (T, error) {
p.wg.Wait()
return p.result, p.err
}
type tuple[T1, T2 any] struct {
_1 T1
_2 T2
}
// All resolves when all of the promises have resolved, reject immediately upon any of the input promises rejecting.
func All[T any](promises []*Promise[T]) *Promise[[]T] {
if len(promises) == 0 {
return nil
}
return New(func(resolve func([]T), reject func(error)) {
valsChan := make(chan tuple[T, int], len(promises))
errsChan := make(chan error, 1)
for idx, p := range promises {
idx := idx
_ = Then(p, func(data T) T {
valsChan <- tuple[T, int]{_1: data, _2: idx}
return data
})
_ = Catch(p, func(err error) error {
errsChan <- err
return err
})
}
resolutions := make([]T, len(promises))
for idx := 0; idx < len(promises); idx++ {
select {
case val := <-valsChan:
resolutions[val._2] = val._1
case err := <-errsChan:
reject(err)
return
}
}
resolve(resolutions)
})
}
// Race will settle the first fullfiled promise among muti promises.
func Race[T any](promises []*Promise[T]) *Promise[T] {
if len(promises) == 0 {
return nil
}
return New(func(resolve func(T), reject func(error)) {
valsChan := make(chan T, 1)
errsChan := make(chan error, 1)
for _, p := range promises {
_ = Then(p, func(data T) T {
valsChan <- data
return data
})
_ = Catch(p, func(err error) error {
errsChan <- err
return err
})
}
select {
case val := <-valsChan:
resolve(val)
case err := <-errsChan:
reject(err)
}
})
}
// Any resolves as soon as any of the input's Promises resolve, with the value of the resolved Promise.
// Any rejects if all of the given Promises are rejected with a combination of all errors.
func Any[T any](promises []*Promise[T]) *Promise[T] {
if len(promises) == 0 {
return nil
}
return New(func(resolve func(T), reject func(error)) {
valsChan := make(chan T, 1)
errsChan := make(chan tuple[error, int], len(promises))
for idx, p := range promises {
idx := idx
_ = Then(p, func(data T) T {
valsChan <- data
return data
})
_ = Catch(p, func(err error) error {
errsChan <- tuple[error, int]{_1: err, _2: idx}
return err
})
}
errs := make([]error, len(promises))
for idx := 0; idx < len(promises); idx++ {
select {
case val := <-valsChan:
resolve(val)
return
case err := <-errsChan:
errs[err._2] = err._1
}
}
errCombo := errs[0]
for _, err := range errs[1:] {
errCombo = internal.JoinError(err)
}
reject(errCombo)
})
}

View File

@@ -0,0 +1,195 @@
package promise
import (
"errors"
"fmt"
"time"
"github.com/duke-git/lancet/v2/internal"
)
func ExampleNew() {
p := New(func(resolve func(string), reject func(error)) {
resolve("hello")
})
val, err := p.Await()
if err != nil {
return
}
fmt.Println(val)
// Output:
// hello
}
func ExampleThen() {
p1 := New(func(resolve func(string), reject func(error)) {
resolve("hello ")
})
p2 := Then(p1, func(s string) string {
return s + "world"
})
result, err := p2.Await()
if err != nil {
return
}
fmt.Println(result)
// Output:
// hello world
}
func ExamplePromise_Then() {
p1 := New(func(resolve func(string), reject func(error)) {
resolve("hello ")
})
p2 := p1.Then(func(s string) string {
return s + "world"
})
result, err := p2.Await()
if err != nil {
return
}
fmt.Println(result)
// Output:
// hello world
}
func ExampleCatch() {
p1 := New(func(resolve func(string), reject func(error)) {
err := errors.New("error1")
reject(err)
})
p2 := Catch(p1, func(err error) error {
e := errors.New("error2")
return internal.JoinError(err, e)
})
_, err := p1.Await()
fmt.Println(err.Error())
result2, err := p2.Await()
fmt.Println(result2)
fmt.Println(err.Error())
// Output:
// error1
//
// error1
// error2
}
func ExamplePromise_Catch() {
p1 := New(func(resolve func(string), reject func(error)) {
err := errors.New("error1")
reject(err)
})
p2 := p1.Catch(func(err error) error {
e := errors.New("error2")
return internal.JoinError(err, e)
})
_, err := p1.Await()
fmt.Println(err.Error())
result2, err := p2.Await()
fmt.Println(result2)
fmt.Println(err.Error())
// Output:
// error1
//
// error1
// error2
}
func ExampleAll() {
p1 := New(func(resolve func(string), reject func(error)) {
resolve("a")
})
p2 := New(func(resolve func(string), reject func(error)) {
resolve("b")
})
p3 := New(func(resolve func(string), reject func(error)) {
resolve("c")
})
pms := []*Promise[string]{p1, p2, p3}
p := All(pms)
result, err := p.Await()
if err != nil {
return
}
fmt.Println(result)
// Output:
// [a b c]
}
func ExampleAny() {
p1 := New(func(resolve func(string), reject func(error)) {
time.Sleep(time.Millisecond * 250)
resolve("fast")
})
p2 := New(func(resolve func(string), reject func(error)) {
time.Sleep(time.Millisecond * 500)
resolve("slow")
})
p3 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error"))
})
pms := []*Promise[string]{p1, p2, p3}
p := Any(pms)
result, err := p.Await()
if err != nil {
return
}
fmt.Println(result)
// Output:
// fast
}
func ExampleRace() {
p1 := New(func(resolve func(string), reject func(error)) {
time.Sleep(time.Millisecond * 100)
resolve("fast")
})
p2 := New(func(resolve func(string), reject func(error)) {
time.Sleep(time.Millisecond * 300)
resolve("slow")
})
pms := []*Promise[string]{p1, p2}
p := Race(pms)
result, err := p.Await()
if err != nil {
return
}
fmt.Println(result)
// Output:
// fast
}

302
promise/promise_test.go Normal file
View File

@@ -0,0 +1,302 @@
package promise
import (
"errors"
"testing"
"time"
"github.com/duke-git/lancet/v2/internal"
)
func TestResolve(t *testing.T) {
assert := internal.NewAssert(t, "TestResolve")
p := Resolve("abc")
assert.Equal("abc", p.result)
assert.Equal(false, p.pending)
}
func TestReject(t *testing.T) {
assert := internal.NewAssert(t, "TestReject")
err := errors.New("error")
p := Reject[string](err)
assert.Equal("error", p.err.Error())
assert.Equal(false, p.pending)
}
func TestThen(t *testing.T) {
assert := internal.NewAssert(t, "TestThen")
p1 := New(func(resolve func(string), reject func(error)) {
resolve("abc")
})
p2 := Then(p1, func(data string) string {
return data + "de"
})
val, err := p1.Await()
assert.IsNil(err)
assert.Equal("abc", val)
val, err = p2.Await()
assert.IsNil(err)
assert.Equal("abcde", val)
}
func TestPromise_Then(t *testing.T) {
assert := internal.NewAssert(t, "TestPromise_Then")
p1 := New(func(resolve func(int), reject func(error)) {
resolve(1)
})
p2 := p1.Then(func(n int) int {
return n + 2
})
val, err := p1.Await()
assert.IsNil(err)
assert.Equal(1, val)
val, err = p2.Await()
assert.IsNil(err)
assert.Equal(3, val)
}
func TestCatch(t *testing.T) {
assert := internal.NewAssert(t, "TestCatch")
p1 := New(func(resolve func(string), reject func(error)) {
err := errors.New("error1")
reject(err)
})
p2 := Catch(p1, func(err error) error {
e := errors.New("error2")
return internal.JoinError(err, e)
})
val, err := p1.Await()
assert.Equal("", val)
assert.IsNotNil(err)
assert.Equal("error1", err.Error())
val, err = p2.Await()
assert.Equal("", val)
assert.IsNotNil(err)
assert.Equal("error1\nerror2", err.Error())
}
func TestPromise_Catch(t *testing.T) {
assert := internal.NewAssert(t, "TestPromise_Catch")
p1 := New(func(resolve func(string), reject func(error)) {
err := errors.New("error1")
reject(err)
})
p2 := p1.Catch(func(err error) error {
e := errors.New("error2")
return internal.JoinError(err, e)
})
val, err := p1.Await()
assert.Equal("", val)
assert.IsNotNil(err)
assert.Equal("error1", err.Error())
val, err = p2.Await()
assert.Equal("", val)
assert.IsNotNil(err)
assert.Equal("error1\nerror2", err.Error())
}
func TestAll(t *testing.T) {
assert := internal.NewAssert(t, "TestPromise_All")
t.Run("AllPromisesFullfilled", func(_ *testing.T) {
p1 := New(func(resolve func(string), reject func(error)) {
resolve("a")
})
p2 := New(func(resolve func(string), reject func(error)) {
resolve("b")
})
p3 := New(func(resolve func(string), reject func(error)) {
resolve("c")
})
p := All([]*Promise[string]{p1, p2, p3})
val, err := p.Await()
assert.Equal([]string{"a", "b", "c"}, val)
assert.IsNil(err)
})
t.Run("EmptyPromises", func(_ *testing.T) {
var empty = []*Promise[any]{}
p := All(empty)
assert.IsNil(p)
})
t.Run("PromisesContainRejected", func(_ *testing.T) {
p1 := New(func(resolve func(string), reject func(error)) {
resolve("a")
})
p2 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error1"))
})
p3 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error2"))
})
p := All([]*Promise[string]{p1, p2, p3})
_, err := p.Await()
assert.IsNotNil(err)
// assert.Equal("error1", err.Error())
})
t.Run("PromisesOnlyRejected", func(_ *testing.T) {
p1 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error1"))
})
p2 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error2"))
})
p3 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error3"))
})
p := All([]*Promise[string]{p1, p2, p3})
_, err := p.Await()
assert.IsNotNil(err)
// assert.Equal("error1", err.Error())
})
}
func TestAny(t *testing.T) {
assert := internal.NewAssert(t, "TestPromise_Any")
t.Run("AnyFullfilled", func(_ *testing.T) {
p1 := New(func(resolve func(string), reject func(error)) {
time.Sleep(time.Millisecond * 250)
resolve("fast")
})
p2 := New(func(resolve func(string), reject func(error)) {
time.Sleep(time.Millisecond * 500)
resolve("slow")
})
p3 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error"))
})
p := Any([]*Promise[string]{p1, p2, p3})
val, err := p.Await()
assert.Equal("fast", val)
assert.IsNil(err)
})
t.Run("EmptyPromises", func(_ *testing.T) {
var empty = []*Promise[any]{}
p := Any(empty)
assert.IsNil(p)
})
t.Run("OnlyRejected", func(_ *testing.T) {
p1 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error1"))
})
p2 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error2"))
})
p := Any([]*Promise[string]{p1, p2})
_, err := p.Await()
assert.IsNotNil(err)
// assert.Equal("error1", err.Error())
})
}
func TestRace(t *testing.T) {
assert := internal.NewAssert(t, "TestPromise_Race")
t.Run("PromisesFullfilled", func(_ *testing.T) {
p1 := New(func(resolve func(string), reject func(error)) {
time.Sleep(time.Millisecond * 100)
resolve("a")
})
p2 := New(func(resolve func(string), reject func(error)) {
time.Sleep(time.Millisecond * 300)
resolve("b")
})
p := Race([]*Promise[string]{p1, p2})
val, err := p.Await()
assert.Equal("a", val)
assert.IsNil(err)
})
t.Run("EmptyPromises", func(_ *testing.T) {
var empty = []*Promise[any]{}
p := Race(empty)
assert.IsNil(p)
})
t.Run("PromisesContainRejected", func(_ *testing.T) {
p1 := New(func(resolve func(string), reject func(error)) {
time.Sleep(time.Millisecond * 100)
resolve("a")
})
p2 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error1"))
})
p3 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error2"))
})
p := Race([]*Promise[string]{p1, p2, p3})
val, err := p.Await()
assert.IsNotNil(err)
// assert.Equal("error1", err.Error())
assert.Equal("", val)
})
t.Run("PromisesOnlyRejected", func(_ *testing.T) {
p1 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error1"))
})
p2 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error2"))
})
p3 := New(func(resolve func(string), reject func(error)) {
reject(errors.New("error3"))
})
p := Race([]*Promise[string]{p1, p2, p3})
_, err := p.Await()
assert.IsNotNil(err)
// assert.Equal("error1", err.Error())
})
}

View File

@@ -57,7 +57,6 @@ func TestRandNumeralOrLetter(t *testing.T) {
reg := regexp.MustCompile(pattern)
randStr := RandNumeralOrLetter(10)
t.Log(randStr)
assert := internal.NewAssert(t, "TestRandNumeralOrLetter")
assert.Equal(10, len(randStr))
@@ -68,7 +67,6 @@ func TestRandInt(t *testing.T) {
assert := internal.NewAssert(t, "TestRandInt")
r1 := RandInt(1, 10)
t.Log(r1)
assert.GreaterOrEqual(r1, 1)
assert.Less(r1, 10)
@@ -99,7 +97,6 @@ func TestUUIdV4(t *testing.T) {
uuid, err := UUIdV4()
if err != nil {
t.Log(err)
t.Fail()
}

View File

@@ -22,7 +22,7 @@ var (
)
// Contain check if the target value is in the slice or not.
// Play: todo
// Play: https://go.dev/play/p/_454yEHcNjf
func Contain[T comparable](slice []T, target T) bool {
for _, item := range slice {
if item == target {
@@ -34,6 +34,7 @@ func Contain[T comparable](slice []T, target T) bool {
}
// ContainBy returns true if predicate function return true.
// Play: https://go.dev/play/p/49tkHfX4GNc
func ContainBy[T any](slice []T, predicate func(item T) bool) bool {
for _, item := range slice {
if predicate(item) {
@@ -318,7 +319,27 @@ 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.
// Play: https://go.dev/play/p/CBKeBoHVLgq
// Deprecated
func Find[T any](slice []T, predicate func(index int, item T) bool) (*T, bool) {
v, ok := FindBy(slice, predicate)
return &v, ok
}
// FindLast iterates over elements of slice from end to begin,
// return the first one that passes a truth test on predicate function.
// If return T is nil then no items matched the predicate func.
// Play: https://go.dev/play/p/FFDPV_j7URd
// Deprecated
func FindLast[T any](slice []T, predicate func(index int, item T) bool) (*T, bool) {
v, ok := FindLastBy(slice, predicate)
return &v, ok
}
// FindBy iterates over elements of slice, returning the first one that passes a truth test on predicate function.
// If return T is nil or zero value then no items matched the predicate func.
// In contrast to Find or FindLast, its return value no longer requires dereferencing
// Play: https://go.dev/play/p/n1lysBYl-GB
func FindBy[T any](slice []T, predicate func(index int, item T) bool) (v T, ok bool) {
index := -1
for i, v := range slice {
@@ -329,17 +350,17 @@ func Find[T any](slice []T, predicate func(index int, item T) bool) (*T, bool) {
}
if index == -1 {
return nil, false
return v, false
}
return &slice[index], true
return slice[index], true
}
// FindLast iterates over elements of slice from end to begin,
// return the first one that passes a truth test on predicate function.
// If return T is nil then no items matched the predicate func.
// Play: https://go.dev/play/p/FFDPV_j7URd
func FindLast[T any](slice []T, predicate func(index int, item T) bool) (*T, bool) {
// FindLastBy iterates over elements of slice, returning the last one that passes a truth test on predicate function.
// If return T is nil or zero value then no items matched the predicate func.
// In contrast to Find or FindLast, its return value no longer requires dereferencing
// Play: https://go.dev/play/p/8iqomzyCl_s
func FindLastBy[T any](slice []T, predicate func(index int, item T) bool) (v T, ok bool) {
index := -1
for i := len(slice) - 1; i >= 0; i-- {
@@ -350,10 +371,10 @@ func FindLast[T any](slice []T, predicate func(index int, item T) bool) (*T, boo
}
if index == -1 {
return nil, false
return v, false
}
return &slice[index], true
return slice[index], true
}
// Flatten flattens slice with one level.
@@ -420,6 +441,17 @@ func ForEach[T any](slice []T, iteratee func(index int, item T)) {
}
}
// ForEachWithBreak iterates over elements of slice and invokes function for each element,
// when iteratee return false, will break the for each loop.
// Play: https://go.dev/play/p/qScs39f3D9W
func ForEachWithBreak[T any](slice []T, iteratee func(index int, item T) bool) {
for i, v := range slice {
if !iteratee(i, v) {
break
}
}
}
// Map creates an slice of values by running each element of slice thru iteratee function.
// Play: https://go.dev/play/p/biaTefqPquw
func Map[T any, U any](slice []T, iteratee func(index int, item T) U) []U {
@@ -436,7 +468,7 @@ func Map[T any, U any](slice []T, iteratee func(index int, item T) U) []U {
// iteratee callback function should returntwo values:
// 1, mapping result.
// 2, whether the result element should be included or not
// Play: todo
// Play: https://go.dev/play/p/J94SZ_9MiIe
func FilterMap[T any, U any](slice []T, iteratee func(index int, item T) (U, bool)) []U {
result := []U{}
@@ -450,7 +482,7 @@ func FilterMap[T any, U any](slice []T, iteratee func(index int, item T) (U, boo
}
// FlatMap manipulates a slice and transforms and flattens it to a slice of another type.
// Play: todo
// Play: https://go.dev/play/p/_QARWlWs1N_F
func FlatMap[T any, U any](slice []T, iteratee func(index int, item T) []U) []U {
result := make([]U, 0, len(slice))
@@ -480,6 +512,30 @@ func Reduce[T any](slice []T, iteratee func(index int, item1, item2 T) T, initia
return result
}
// ReduceBy produces a value from slice by accumulating the result of each element as passed through the reducer function.
// Play: https://go.dev/play/p/YKDpLi7gtee
func ReduceBy[T any, U any](slice []T, initial U, reducer func(index int, item T, agg U) U) U {
accumulator := initial
for i, v := range slice {
accumulator = reducer(i, v, accumulator)
}
return accumulator
}
// ReduceRight is like ReduceBy, but it iterates over elements of slice from right to left.
// Play: https://go.dev/play/p/qT9dZC03A1K
func ReduceRight[T any, U any](slice []T, initial U, reducer func(index int, item T, agg U) U) U {
accumulator := initial
for i := len(slice) - 1; i >= 0; i-- {
accumulator = reducer(i, slice[i], accumulator)
}
return accumulator
}
// Replace returns a copy of the slice with the first n non-overlapping instances of old replaced by new.
// Play: https://go.dev/play/p/P5mZp7IhOFo
func Replace[T comparable](slice []T, old T, new T, n int) []T {
@@ -1082,7 +1138,7 @@ func IndexOf[T comparable](arr []T, val 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.
// Play: https://go.dev/play/p/DokM4cf1IKH
func LastIndexOf[T comparable](slice []T, item T) int {
for i := len(slice) - 1; i > 0; i-- {
for i := len(slice) - 1; i >= 0; i-- {
if item == slice[i] {
return i
}

View File

@@ -341,6 +341,40 @@ func ExampleFindLast() {
// true
}
func ExampleFindBy() {
nums := []int{1, 2, 3, 4, 5}
isEven := func(i, num int) bool {
return num%2 == 0
}
result, ok := FindBy(nums, isEven)
fmt.Println(result)
fmt.Println(ok)
// Output:
// 2
// true
}
func ExampleFindLastBy() {
nums := []int{1, 2, 3, 4, 5}
isEven := func(i, num int) bool {
return num%2 == 0
}
result, ok := FindLastBy(nums, isEven)
fmt.Println(result)
fmt.Println(ok)
// Output:
// 4
// true
}
func ExampleFlatten() {
arrs := [][][]string{{{"a", "b"}}, {{"c", "d"}}}
@@ -379,6 +413,25 @@ func ExampleForEach() {
// [2 3 4]
}
func ExampleForEachWithBreak() {
numbers := []int{1, 2, 3, 4, 5}
var sum int
ForEachWithBreak(numbers, func(_, n int) bool {
if n > 3 {
return false
}
sum += n
return true
})
fmt.Println(sum)
// Output:
// 6
}
func ExampleMap() {
nums := []int{1, 2, 3}
@@ -441,6 +494,34 @@ func ExampleReduce() {
// 6
}
func ExampleReduceBy() {
result1 := ReduceBy([]int{1, 2, 3, 4}, 0, func(_ int, item int, agg int) int {
return agg + item
})
result2 := ReduceBy([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 10
// 1234
}
func ExampleReduceRight() {
result := ReduceRight([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
fmt.Println(result)
// Output:
// 4321
}
func ExampleReplace() {
strs := []string{"a", "b", "c", "a"}

View File

@@ -249,6 +249,44 @@ func TestFind(t *testing.T) {
assert.Equal(2, *res)
}
func TestFindBy(t *testing.T) {
assert := internal.NewAssert(t, "TestFindBy")
nums := []int{1, 2, 3, 4, 5}
even := func(i, num int) bool {
return num%2 == 0
}
res, ok := FindBy(nums, even)
if !ok {
t.Fatal("found nothing")
}
assert.Equal(2, res)
res, ok = FindBy(nums, func(_ int, v int) bool {
return v == 6
})
assert.Equal(res == 0 && ok == false, true)
}
func TestFindLastBy(t *testing.T) {
assert := internal.NewAssert(t, "TestFindBy")
nums := []int{1, 2, 3, 4, 5}
even := func(i, num int) bool {
return num%2 == 0
}
res, ok := FindLastBy(nums, even)
if !ok {
t.Fatal("found nothing")
}
assert.Equal(4, res)
res, ok = FindLastBy(nums, func(_ int, v int) bool {
return v == 6
})
assert.Equal(res == 0 && ok == false, true)
}
func TestFindLast(t *testing.T) {
nums := []int{1, 2, 3, 4, 5}
even := func(i, num int) bool {
@@ -307,6 +345,23 @@ func TestForEach(t *testing.T) {
assert.Equal(expected, numbersAddTwo)
}
func TestForEachWithBreak(t *testing.T) {
numbers := []int{1, 2, 3, 4, 5}
var sum int
ForEachWithBreak(numbers, func(_, n int) bool {
if n > 3 {
return false
}
sum += n
return true
})
assert := internal.NewAssert(t, "TestForEach")
assert.Equal(6, sum)
}
func TestMap(t *testing.T) {
nums := []int{1, 2, 3, 4}
multiplyTwo := func(i, num int) int {
@@ -388,6 +443,32 @@ func TestReduce(t *testing.T) {
}
}
func TestReduceBy(t *testing.T) {
assert := internal.NewAssert(t, "TestReduceBy")
result1 := ReduceBy([]int{1, 2, 3, 4}, 0, func(_ int, item int, agg int) int {
return agg + item
})
result2 := ReduceBy([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
assert.Equal(10, result1)
assert.Equal("1234", result2)
}
func TestReduceRight(t *testing.T) {
assert := internal.NewAssert(t, "ReduceRight")
result := ReduceRight([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
assert.Equal("4321", result)
}
func TestIntSlice(t *testing.T) {
var nums []any
nums = append(nums, 1, 2, 3)
@@ -513,7 +594,6 @@ func TestInsertAt(t *testing.T) {
assert.Equal([]string{"a", "b", "c", "1"}, InsertAt(strs, 3, "1"))
assert.Equal([]string{"1", "2", "3", "a", "b", "c"}, InsertAt(strs, 0, []string{"1", "2", "3"}))
assert.Equal([]string{"a", "b", "c", "1", "2", "3"}, InsertAt(strs, 3, []string{"1", "2", "3"}))
t.Log(strs)
}
func TestUpdateAt(t *testing.T) {
@@ -648,8 +728,8 @@ func TestDifferenceWith(t *testing.T) {
func TestDifferenceBy(t *testing.T) {
assert := internal.NewAssert(t, "TestDifferenceBy")
s1 := []int{1, 2, 3, 4, 5} //after add one: 2 3 4 5 6
s2 := []int{3, 4, 5} //after add one: 4 5 6
s1 := []int{1, 2, 3, 4, 5} // after add one: 2 3 4 5 6
s2 := []int{3, 4, 5} // after add one: 4 5 6
addOne := func(i int, v int) int {
return v + 1
}
@@ -740,10 +820,9 @@ func TestSortBy(t *testing.T) {
return a.Age < b.Age
})
t.Logf("sort users by age: %v", users)
// output
// [{b 15} {a 21} {c 100}]
assert.EqualValues(15, users[0].Age)
assert.EqualValues(21, users[1].Age)
assert.EqualValues(100, users[2].Age)
}
func TestSortByFielDesc(t *testing.T) {
@@ -809,7 +888,6 @@ func TestShuffle(t *testing.T) {
s := []int{1, 2, 3, 4, 5}
res := Shuffle(s)
t.Log("Shuffle result: ", res)
assert.Equal(5, len(res))
}
@@ -856,8 +934,9 @@ func TestIndexOf(t *testing.T) {
func TestLastIndexOf(t *testing.T) {
assert := internal.NewAssert(t, "TestLastIndexOf")
arr := []string{"a", "a", "b", "c"}
assert.Equal(1, LastIndexOf(arr, "a"))
arr := []string{"a", "b", "b", "c"}
assert.Equal(0, LastIndexOf(arr, "a"))
assert.Equal(2, LastIndexOf(arr, "b"))
assert.Equal(-1, LastIndexOf(arr, "d"))
}

View File

@@ -1,9 +1,8 @@
// Copyright 2023 dudaodong@gmail.com. All rights resulterved.
// Use of this source code is governed by MIT license
// Package stream implements a sequence of elements supporting sequential and parallel aggregate operations.
// this package is an experiment to explore if stream in go can work as the way java does. it's complete, but not
// powerful like other libs
// Package stream implements a sequence of elements supporting sequential and operations.
// this package is an experiment to explore if stream in go can work as the way java does. its function is very limited.
package stream
import (
@@ -52,18 +51,20 @@ type stream[T any] struct {
source []T
}
// Of creates a stream stream whose elements are the specified values.
// Of creates a stream whose elements are the specified values.
// Play: https://go.dev/play/p/jI6_iZZuVFE
func Of[T any](elems ...T) stream[T] {
return FromSlice(elems)
}
// Generate stream where each element is generated by the provided generater function
// generater function: func() func() (item T, ok bool) {}
// Play: https://go.dev/play/p/rkOWL1yA3j9
func Generate[T any](generator func() func() (item T, ok bool)) stream[T] {
source := make([]T, 0)
var zeroValue T
for next, item, ok := generator(), zeroValue, true; ok; {
item, ok = next()
if ok {
source = append(source, item)
@@ -74,11 +75,13 @@ func Generate[T any](generator func() func() (item T, ok bool)) stream[T] {
}
// FromSlice creates stream from slice.
// Play: https://go.dev/play/p/wywTO0XZtI4
func FromSlice[T any](source []T) stream[T] {
return stream[T]{source: source}
}
// FromChannel creates stream from channel.
// Play: https://go.dev/play/p/9TZYugGMhXZ
func FromChannel[T any](source <-chan T) stream[T] {
s := make([]T, 0)
@@ -90,6 +93,7 @@ func FromChannel[T any](source <-chan T) stream[T] {
}
// FromRange creates a number stream from start to end. both start and end are included. [start, end]
// Play: https://go.dev/play/p/9Ex1-zcg-B-
func FromRange[T constraints.Integer | constraints.Float](start, end, step T) stream[T] {
if end < start {
panic("stream.FromRange: param start should be before param end")
@@ -98,7 +102,7 @@ func FromRange[T constraints.Integer | constraints.Float](start, end, step T) st
}
l := int((end-start)/step) + 1
source := make([]T, l, l)
source := make([]T, l)
for i := 0; i < l; i++ {
source[i] = start + (T(i) * step)
@@ -108,6 +112,7 @@ func FromRange[T constraints.Integer | constraints.Float](start, end, step T) st
}
// Concat creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
// Play: https://go.dev/play/p/HM4OlYk_OUC
func Concat[T any](a, b stream[T]) stream[T] {
source := make([]T, 0)
@@ -118,6 +123,7 @@ func Concat[T any](a, b stream[T]) stream[T] {
}
// Distinct returns a stream that removes the duplicated items.
// Play: https://go.dev/play/p/eGkOSrm64cB
func (s stream[T]) Distinct() stream[T] {
source := make([]T, 0)
@@ -146,6 +152,7 @@ func hashKey(data any) string {
}
// Filter returns a stream consisting of the elements of this stream that match the given predicate.
// Play: https://go.dev/play/p/MFlSANo-buc
func (s stream[T]) Filter(predicate func(item T) bool) stream[T] {
source := make([]T, 0)
@@ -159,8 +166,9 @@ func (s stream[T]) Filter(predicate func(item T) bool) stream[T] {
}
// Map returns a stream consisting of the elements of this stream that apply the given function to elements of stream.
// Play: https://go.dev/play/p/OtNQUImdYko
func (s stream[T]) Map(mapper func(item T) T) stream[T] {
source := make([]T, s.Count(), s.Count())
source := make([]T, s.Count())
for i, v := range s.source {
source[i] = mapper(v)
@@ -170,6 +178,7 @@ func (s stream[T]) Map(mapper func(item T) T) stream[T] {
}
// Peek returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
// Play: https://go.dev/play/p/u1VNzHs6cb2
func (s stream[T]) Peek(consumer func(item T)) stream[T] {
for _, v := range s.source {
consumer(v)
@@ -180,6 +189,7 @@ func (s stream[T]) Peek(consumer func(item T)) stream[T] {
// Skip returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream.
// If this stream contains fewer than n elements then an empty stream will be returned.
// Play: https://go.dev/play/p/fNdHbqjahum
func (s stream[T]) Skip(n int) stream[T] {
if n <= 0 {
return s
@@ -200,6 +210,7 @@ func (s stream[T]) Skip(n int) stream[T] {
}
// Limit returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.
// Play: https://go.dev/play/p/qsO4aniDcGf
func (s stream[T]) Limit(maxSize int) stream[T] {
if s.source == nil {
return s
@@ -219,6 +230,7 @@ func (s stream[T]) Limit(maxSize int) stream[T] {
}
// AllMatch returns whether all elements of this stream match the provided predicate.
// Play: https://go.dev/play/p/V5TBpVRs-Cx
func (s stream[T]) AllMatch(predicate func(item T) bool) bool {
for _, v := range s.source {
if !predicate(v) {
@@ -230,6 +242,7 @@ func (s stream[T]) AllMatch(predicate func(item T) bool) bool {
}
// AnyMatch returns whether any elements of this stream match the provided predicate.
// Play: https://go.dev/play/p/PTCnWn4OxSn
func (s stream[T]) AnyMatch(predicate func(item T) bool) bool {
for _, v := range s.source {
if predicate(v) {
@@ -241,11 +254,13 @@ func (s stream[T]) AnyMatch(predicate func(item T) bool) bool {
}
// NoneMatch returns whether no elements of this stream match the provided predicate.
// Play: https://go.dev/play/p/iWS64pL1oo3
func (s stream[T]) NoneMatch(predicate func(item T) bool) bool {
return !s.AnyMatch(predicate)
}
// ForEach performs an action for each element of this stream.
// Play: https://go.dev/play/p/Dsm0fPqcidk
func (s stream[T]) ForEach(action func(item T)) {
for _, v := range s.source {
action(v)
@@ -253,20 +268,23 @@ func (s stream[T]) ForEach(action func(item T)) {
}
// Reduce performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.
func (s stream[T]) Reduce(init T, accumulator func(a, b T) T) T {
// Play: https://go.dev/play/p/6uzZjq_DJLU
func (s stream[T]) Reduce(initial T, accumulator func(a, b T) T) T {
for _, v := range s.source {
init = accumulator(init, v)
initial = accumulator(initial, v)
}
return init
return initial
}
// Count returns the count of elements in the stream.
// Play: https://go.dev/play/p/r3koY6y_Xo-
func (s stream[T]) Count() int {
return len(s.source)
}
// FindFirst returns the first element of this stream and true, or zero value and false if the stream is empty.
// Play: https://go.dev/play/p/9xEf0-6C1e3
func (s stream[T]) FindFirst() (T, bool) {
var result T
@@ -277,7 +295,20 @@ func (s stream[T]) FindFirst() (T, bool) {
return s.source[0], true
}
// FindLast returns the last element of this stream and true, or zero value and false if the stream is empty.
// Play: https://go.dev/play/p/9xEf0-6C1e3
func (s stream[T]) FindLast() (T, bool) {
var result T
if s.source == nil || len(s.source) == 0 {
return result, false
}
return s.source[len(s.source)-1], true
}
// Reverse returns a stream whose elements are reverse order of given stream.
// Play: https://go.dev/play/p/A8_zkJnLHm4
func (s stream[T]) Reverse() stream[T] {
l := len(s.source)
source := make([]T, l)
@@ -289,6 +320,7 @@ func (s stream[T]) Reverse() stream[T] {
}
// Range returns a stream whose elements are in the range from start(included) to end(excluded) original stream.
// Play: https://go.dev/play/p/indZY5V2f4j
func (s stream[T]) Range(start, end int) stream[T] {
if start < 0 {
start = 0
@@ -314,6 +346,7 @@ func (s stream[T]) Range(start, end int) stream[T] {
}
// Sorted returns a stream consisting of the elements of this stream, sorted according to the provided less function.
// Play: https://go.dev/play/p/XXtng5uonFj
func (s stream[T]) Sorted(less func(a, b T) bool) stream[T] {
source := []T{}
source = append(source, s.source...)
@@ -325,6 +358,7 @@ func (s stream[T]) Sorted(less func(a, b T) bool) stream[T] {
// Max returns the maximum element of this stream according to the provided less function.
// less: a > b
// Play: https://go.dev/play/p/fm-1KOPtGzn
func (s stream[T]) Max(less func(a, b T) bool) (T, bool) {
var max T
@@ -342,6 +376,7 @@ func (s stream[T]) Max(less func(a, b T) bool) (T, bool) {
// Min returns the minimum element of this stream according to the provided less function.
// less: a < b
// Play: https://go.dev/play/p/vZfIDgGNRe_0
func (s stream[T]) Min(less func(a, b T) bool) (T, bool) {
var min T
@@ -359,6 +394,7 @@ func (s stream[T]) Min(less func(a, b T) bool) (T, bool) {
}
// ToSlice return the elements in the stream.
// Play: https://go.dev/play/p/jI6_iZZuVFE
func (s stream[T]) ToSlice() []T {
return s.source
}

View File

@@ -0,0 +1,386 @@
package stream
import (
"fmt"
)
func ExampleOf() {
s := Of(1, 2, 3)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
func ExampleFromSlice() {
s := FromSlice([]int{1, 2, 3})
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
func ExampleFromChannel() {
ch := make(chan int)
go func() {
for i := 1; i < 4; i++ {
ch <- i
}
close(ch)
}()
s := FromChannel(ch)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
func ExampleFromRange() {
s := FromRange(1, 5, 1)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3 4 5]
}
func ExampleGenerate() {
n := 0
max := 4
generator := func() func() (int, bool) {
return func() (int, bool) {
n++
return n, n < max
}
}
s := Generate(generator)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3]
}
func ExampleConcat() {
s1 := FromSlice([]int{1, 2, 3})
s2 := FromSlice([]int{4, 5, 6})
s := Concat(s1, s2)
data := s.ToSlice()
fmt.Println(data)
// Output:
// [1 2 3 4 5 6]
}
func ExampleStream_Distinct() {
original := FromSlice([]int{1, 2, 2, 3, 3, 3})
distinct := original.Distinct()
data1 := original.ToSlice()
data2 := distinct.ToSlice()
fmt.Println(data1)
fmt.Println(data2)
// Output:
// [1 2 2 3 3 3]
// [1 2 3]
}
func ExampleStream_Filter() {
original := FromSlice([]int{1, 2, 3, 4, 5})
isEven := func(n int) bool {
return n%2 == 0
}
even := original.Filter(isEven)
fmt.Println(even.ToSlice())
// Output:
// [2 4]
}
func ExampleStream_Map() {
original := FromSlice([]int{1, 2, 3})
addOne := func(n int) int {
return n + 1
}
increament := original.Map(addOne)
fmt.Println(increament.ToSlice())
// Output:
// [2 3 4]
}
func ExampleStream_Peek() {
original := FromSlice([]int{1, 2, 3})
data := []string{}
peekStream := original.Peek(func(n int) {
data = append(data, fmt.Sprint("value", n))
})
fmt.Println(original.ToSlice())
fmt.Println(peekStream.ToSlice())
fmt.Println(data)
// Output:
// [1 2 3]
// [1 2 3]
// [value1 value2 value3]
}
func ExampleStream_Skip() {
original := FromSlice([]int{1, 2, 3, 4})
s1 := original.Skip(-1)
s2 := original.Skip(0)
s3 := original.Skip(1)
s4 := original.Skip(5)
fmt.Println(s1.ToSlice())
fmt.Println(s2.ToSlice())
fmt.Println(s3.ToSlice())
fmt.Println(s4.ToSlice())
// Output:
// [1 2 3 4]
// [1 2 3 4]
// [2 3 4]
// []
}
func ExampleStream_Limit() {
original := FromSlice([]int{1, 2, 3, 4})
s1 := original.Limit(-1)
s2 := original.Limit(0)
s3 := original.Limit(1)
s4 := original.Limit(5)
fmt.Println(s1.ToSlice())
fmt.Println(s2.ToSlice())
fmt.Println(s3.ToSlice())
fmt.Println(s4.ToSlice())
// Output:
// []
// []
// [1]
// [1 2 3 4]
}
func ExampleStream_AllMatch() {
original := FromSlice([]int{1, 2, 3})
result1 := original.AllMatch(func(item int) bool {
return item > 0
})
result2 := original.AllMatch(func(item int) bool {
return item > 1
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
func ExampleStream_AnyMatch() {
original := FromSlice([]int{1, 2, 3})
result1 := original.AnyMatch(func(item int) bool {
return item > 1
})
result2 := original.AnyMatch(func(item int) bool {
return item > 3
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
func ExampleStream_NoneMatch() {
original := FromSlice([]int{1, 2, 3})
result1 := original.NoneMatch(func(item int) bool {
return item > 3
})
result2 := original.NoneMatch(func(item int) bool {
return item > 1
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}
func ExampleStream_ForEach() {
original := FromSlice([]int{1, 2, 3})
result := 0
original.ForEach(func(item int) {
result += item
})
fmt.Println(result)
// Output:
// 6
}
func ExampleStream_Reduce() {
original := FromSlice([]int{1, 2, 3})
result := original.Reduce(0, func(a, b int) int {
return a + b
})
fmt.Println(result)
// Output:
// 6
}
func ExampleStream_FindFirst() {
original := FromSlice([]int{1, 2, 3})
result, ok := original.FindFirst()
fmt.Println(result)
fmt.Println(ok)
// Output:
// 1
// true
}
func ExampleStream_FindLast() {
original := FromSlice([]int{3, 2, 1})
result, ok := original.FindLast()
fmt.Println(result)
fmt.Println(ok)
// Output:
// 1
// true
}
func ExampleStream_Reverse() {
original := FromSlice([]int{1, 2, 3})
reverse := original.Reverse()
fmt.Println(reverse.ToSlice())
// Output:
// [3 2 1]
}
func ExampleStream_Range() {
original := FromSlice([]int{1, 2, 3})
s1 := original.Range(0, 0)
s2 := original.Range(0, 1)
s3 := original.Range(0, 3)
s4 := original.Range(1, 2)
fmt.Println(s1.ToSlice())
fmt.Println(s2.ToSlice())
fmt.Println(s3.ToSlice())
fmt.Println(s4.ToSlice())
// Output:
// []
// [1]
// [1 2 3]
// [2]
}
func ExampleStream_Sorted() {
original := FromSlice([]int{4, 2, 1, 3})
sorted := original.Sorted(func(a, b int) bool { return a < b })
fmt.Println(original.ToSlice())
fmt.Println(sorted.ToSlice())
// Output:
// [4 2 1 3]
// [1 2 3 4]
}
func ExampleStream_Max() {
original := FromSlice([]int{4, 2, 1, 3})
max, ok := original.Max(func(a, b int) bool { return a > b })
fmt.Println(max)
fmt.Println(ok)
// Output:
// 4
// true
}
func ExampleStream_Min() {
original := FromSlice([]int{4, 2, 1, 3})
min, ok := original.Min(func(a, b int) bool { return a < b })
fmt.Println(min)
fmt.Println(ok)
// Output:
// 1
// true
}
func ExampleStream_Count() {
s1 := FromSlice([]int{1, 2, 3})
s2 := FromSlice([]int{})
fmt.Println(s1.Count())
fmt.Println(s2.Count())
// Output:
// 3
// 0
}

View File

@@ -147,13 +147,17 @@ func TestStream_Peek(t *testing.T) {
func TestStream_Skip(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_Peek")
stream := FromSlice([]int{1, 2, 3, 4, 5, 6})
stream := FromSlice([]int{1, 2, 3, 4})
s1 := stream.Skip(-1)
s2 := stream.Skip(0)
s3 := stream.Skip(1)
s4 := stream.Skip(2)
assert.Equal([]int{1, 2, 3, 4, 5, 6}, s1.ToSlice())
assert.Equal([]int{1, 2, 3, 4, 5, 6}, s2.ToSlice())
assert.Equal([]int{1, 2, 3, 4}, s1.ToSlice())
assert.Equal([]int{1, 2, 3, 4}, s2.ToSlice())
assert.Equal([]int{2, 3, 4}, s3.ToSlice())
assert.Equal([]int{3, 4}, s4.ToSlice())
}
func TestStream_Limit(t *testing.T) {
@@ -248,6 +252,16 @@ func TestStream_Reduce(t *testing.T) {
assert.Equal(6, result)
}
func TestStream_Count(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_Count")
s1 := FromSlice([]int{1, 2, 3})
s2 := FromSlice([]int{})
assert.Equal(3, s1.Count())
assert.Equal(0, s2.Count())
}
func TestStream_FindFirst(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_FindFirst")
@@ -259,6 +273,24 @@ func TestStream_FindFirst(t *testing.T) {
assert.Equal(true, ok)
}
func TestStream_FindLast(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_FindLast")
stream := FromSlice([]int{3, 2, 1})
result, ok := stream.FindLast()
assert.Equal(1, result)
assert.Equal(true, ok)
stream2 := FromSlice([]int{})
result, ok = stream2.FindLast()
assert.Equal(0, result)
assert.Equal(false, ok)
}
func TestStream_Reverse(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_Reverse")

112
structs/field.go Normal file
View File

@@ -0,0 +1,112 @@
package structs
import (
"reflect"
"github.com/duke-git/lancet/v2/pointer"
)
// Field is abstract struct field for provide several high level functions
type Field struct {
Struct
field reflect.StructField
tag *Tag
}
func newField(v reflect.Value, f reflect.StructField, tagName string) *Field {
tag := f.Tag.Get(tagName)
field := &Field{
field: f,
tag: newTag(tag),
}
field.rvalue = v
field.rtype = v.Type()
field.TagName = tagName
return field
}
// Tag returns the value that the key in the tag string.
func (f *Field) Tag() *Tag {
return f.tag
}
// Value returns the underlying value of the field.
func (f *Field) Value() any {
return f.rvalue.Interface()
}
// IsEmbedded returns true if the given field is an embedded field.
func (f *Field) IsEmbedded() bool {
return len(f.field.Index) > 1
}
// IsExported returns true if the given field is exported.
func (f *Field) IsExported() bool {
return f.field.IsExported()
}
// IsZero returns true if the given field is zero value.
func (f *Field) IsZero() bool {
z := reflect.Zero(f.rvalue.Type()).Interface()
v := f.Value()
return reflect.DeepEqual(z, v)
}
// Name returns the name of the given field
func (f *Field) Name() string {
return f.field.Name
}
// Kind returns the field's kind
func (f *Field) Kind() reflect.Kind {
return f.rvalue.Kind()
}
// IsSlice check if a struct field type is slice or not
func (f *Field) IsSlice() bool {
k := f.rvalue.Kind()
return k == reflect.Slice
}
// mapValue covert field value to map
func (f *Field) mapValue(value any) any {
val := pointer.ExtractPointer(value)
v := reflect.ValueOf(val)
var ret any
switch v.Kind() {
case reflect.Struct:
s := New(val)
s.TagName = f.TagName
m, _ := s.ToMap()
ret = m
case reflect.Map:
mapEl := v.Type().Elem()
switch mapEl.Kind() {
case reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice, reflect.Chan:
// iterate the map
m := make(map[string]any, v.Len())
for _, key := range v.MapKeys() {
m[key.String()] = f.mapValue(v.MapIndex(key).Interface())
}
ret = m
default:
ret = v.Interface()
}
case reflect.Slice, reflect.Array:
sEl := v.Type().Elem()
switch sEl.Kind() {
case reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice, reflect.Chan:
slices := make([]any, v.Len())
for i := 0; i < v.Len(); i++ {
slices[i] = f.mapValue(v.Index(i).Interface())
}
ret = slices
default:
ret = v.Interface()
}
default:
ret = v.Interface()
}
return ret
}

272
structs/field_test.go Normal file
View File

@@ -0,0 +1,272 @@
package structs
import (
"github.com/duke-git/lancet/v2/internal"
"reflect"
"testing"
)
func TestField_Tag(t *testing.T) {
assert := internal.NewAssert(t, "TestField_Tag")
type Parent struct {
Name string `json:"name,omitempty"`
}
p1 := &Parent{"111"}
s := New(p1)
n, _ := s.Field("Name")
tag := n.Tag()
assert.Equal("name", tag.Name)
assert.Equal(true, tag.HasOption("omitempty"))
}
func TestField_Value(t *testing.T) {
assert := internal.NewAssert(t, "TestField_Value")
type Parent struct {
Name string `json:"name,omitempty"`
}
p1 := &Parent{"111"}
s := New(p1)
n, _ := s.Field("Name")
assert.Equal("111", n.Value())
}
func TestField_IsEmbedded(t *testing.T) {
assert := internal.NewAssert(t, "TestField_IsEmbedded")
type Parent struct {
Name string
}
type Child struct {
Parent
Age int
}
c1 := &Child{}
c1.Name = "111"
c1.Age = 11
s := New(c1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
assert.Equal(true, n.IsEmbedded())
assert.Equal(false, a.IsEmbedded())
}
func TestField_IsExported(t *testing.T) {
assert := internal.NewAssert(t, "TestField_IsEmbedded")
type Parent struct {
Name string
age int
}
p1 := &Parent{Name: "11", age: 11}
s := New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("age")
assert.Equal(true, n.IsExported())
assert.Equal(false, a.IsExported())
}
func TestField_IsZero(t *testing.T) {
assert := internal.NewAssert(t, "TestField_IsZero")
type Parent struct {
Name string
Age int
}
p1 := &Parent{Age: 11}
s := New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
assert.Equal(true, n.IsZero())
assert.Equal(false, a.IsZero())
}
func TestField_Name(t *testing.T) {
assert := internal.NewAssert(t, "TestField_Name")
type Parent struct {
Name string
Age int
}
p1 := &Parent{Age: 11}
s := New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
assert.Equal("Name", n.Name())
assert.Equal("Age", a.Name())
}
func TestField_Kind(t *testing.T) {
assert := internal.NewAssert(t, "TestField_Kind")
type Parent struct {
Name string
Age int
}
p1 := &Parent{Age: 11}
s := New(p1)
n, _ := s.Field("Name")
a, _ := s.Field("Age")
assert.Equal(reflect.String, n.Kind())
assert.Equal(reflect.Int, a.Kind())
}
func TestField_IsSlice(t *testing.T) {
assert := internal.NewAssert(t, "TestField_IsSlice")
type Parent struct {
Name string
arr []int
}
p1 := &Parent{arr: []int{1, 2, 3}}
s := New(p1)
a, _ := s.Field("arr")
assert.Equal(true, a.IsSlice())
}
func TestField_MapValue(t *testing.T) {
assert := internal.NewAssert(t, "TestField_MapValue")
t.Run("nested struct", func(t *testing.T) {
type Child struct {
Name string `json:"name"`
}
type Parent struct {
Name string `json:"name"`
Child *Child `json:"child"`
}
c1 := &Child{"11-1"}
p1 := &Parent{
Name: "11",
Child: c1,
}
s := New(p1)
f, ok := s.Field("Child")
val := f.mapValue(f.Value())
assert.Equal(true, ok)
assert.Equal(map[string]any{"name": "11-1"}, val)
})
t.Run("nested ptr struct", func(t *testing.T) {
type Child struct {
Name string `json:"name"`
}
type Parent struct {
Name string `json:"name"`
Child any `json:"child"`
}
c1 := &Child{"11-1"}
c2 := &c1
c3 := &c2
p1 := &Parent{
Name: "11",
Child: c3,
}
s := New(p1)
f, ok := s.Field("Child")
val := f.mapValue(f.Value())
assert.Equal(true, ok)
assert.Equal(map[string]any{"name": "11-1"}, val)
})
t.Run("nested array", func(t *testing.T) {
type Parent struct {
Name string `json:"name"`
Child []int `json:"child"`
}
p1 := &Parent{
Name: "11",
Child: []int{1, 2, 3},
}
s := New(p1)
f, ok := s.Field("Child")
val := f.mapValue(f.Value())
assert.Equal(true, ok)
assert.Equal([]int{1, 2, 3}, val)
})
t.Run("nested array struct", func(t *testing.T) {
type Child struct {
Name string `json:"name"`
}
type Parent struct {
Name string `json:"name"`
Child []*Child `json:"child"`
}
c1 := &Child{"11-1"}
c2 := &Child{"11-2"}
p1 := &Parent{
Name: "11",
Child: []*Child{c1, c2},
}
s := New(p1)
f, ok := s.Field("Child")
val := f.mapValue(f.Value())
assert.Equal(true, ok)
arr := []any{map[string]any{"name": "11-1"}, map[string]any{"name": "11-2"}}
assert.Equal(arr, val)
})
t.Run("nested ptr array struct", func(t *testing.T) {
type Child struct {
Name string `json:"name"`
}
type Parent struct {
Name string `json:"name"`
Child *[]*Child `json:"child"`
}
c1 := &Child{"11-1"}
c2 := &Child{"11-2"}
p1 := &Parent{
Name: "11",
Child: &[]*Child{c1, c2},
}
s := New(p1)
f, ok := s.Field("Child")
val := f.mapValue(f.Value())
assert.Equal(true, ok)
arr := []any{map[string]any{"name": "11-1"}, map[string]any{"name": "11-2"}}
assert.Equal(arr, val)
})
t.Run("nested map in struct", func(t *testing.T) {
type Parent struct {
Name string `json:"name"`
Child map[string]any `json:"child"`
}
p1 := &Parent{
Name: "11",
Child: map[string]any{"a": 1, "b": map[string]any{"name": "11-1"}},
}
s := New(p1)
f, ok := s.Field("Child")
val := f.mapValue(f.Value())
assert.Equal(true, ok)
assert.Equal(map[string]any{"a": 1, "b": map[string]any{"name": "11-1"}}, val)
})
}

117
structs/struct.go Normal file
View File

@@ -0,0 +1,117 @@
// Package structs provide several high level functions to manipulate struct, tag, and field.
package structs
import (
"reflect"
"github.com/duke-git/lancet/v2/pointer"
)
// defaultTagName is the default tag for struct fields to lookup.
var defaultTagName = "json"
// Struct is abstract struct for provide several high level functions
type Struct struct {
raw any
rtype reflect.Type
rvalue reflect.Value
TagName string
}
// New returns a new *Struct
func New(value any, tagName ...string) *Struct {
value = pointer.ExtractPointer(value)
v := reflect.ValueOf(value)
t := reflect.TypeOf(value)
tn := defaultTagName
if len(tagName) > 0 {
tn = tagName[0]
}
// if need: can also set defaultTagName to tn across structs package level
// defaultTagName = tn
return &Struct{
raw: value,
rtype: t,
rvalue: v,
TagName: tn,
}
}
// ToMap converts the given struct to a map[string]any, where the keys
// of the keys are the field names and the values of the map are the values
// of the fields. The default map key is the struct field name, but you can
// change it. The `json` key is the default tag key. Example:
//
// // default
// Name string `json:"name"`
//
// // ignore the field
// Name string // no tag
// Age string `json:"-"` // json ignore tag
// sex string // unexported field
// Goal int `json:"goal,omitempty"` // omitempty if the field is zero value
//
// // custom map key
// Name string `json:"myName"`
//
// ToMap convert the exported fields of a struct to map.
func (s *Struct) ToMap() (map[string]any, error) {
if !s.IsStruct() {
return nil, errInvalidStruct(s)
}
result := make(map[string]any)
fields := s.Fields()
for _, f := range fields {
if !f.IsExported() || f.tag.IsEmpty() || f.tag.Name == "-" {
continue
}
if f.IsZero() && f.tag.HasOption("omitempty") {
continue
}
result[f.tag.Name] = f.mapValue(f.Value())
}
return result, nil
}
// Fields returns all the struct fields within a slice
func (s *Struct) Fields() []*Field {
var fields []*Field
fieldNum := s.rvalue.NumField()
for i := 0; i < fieldNum; i++ {
v := s.rvalue.Field(i)
sf := s.rtype.Field(i)
field := newField(v, sf, s.TagName)
fields = append(fields, field)
}
return fields
}
// Field returns a Field if the given field name was found
func (s *Struct) Field(name string) (*Field, bool) {
f, ok := s.rtype.FieldByName(name)
if !ok {
return nil, false
}
return newField(s.rvalue.FieldByName(name), f, s.TagName), true
}
// IsStruct returns true if the given rvalue is a struct
func (s *Struct) IsStruct() bool {
k := s.rvalue.Kind()
if k == reflect.Invalid {
return false
}
return k == reflect.Struct
}
// ToMap convert struct to map, only convert exported struct field
// map key is specified same as struct field tag `json` value.
func ToMap(v any) (map[string]any, error) {
return New(v).ToMap()
}

View File

@@ -0,0 +1,7 @@
package structs
import "fmt"
func errInvalidStruct(v any) error {
return fmt.Errorf("invalid struct %v", v)
}

Some files were not shown because too many files have changed in this diff Show More