1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-17 03:02:28 +08:00

Compare commits

...

15 Commits

Author SHA1 Message Date
dudaodong
4c5524354c doc: normalize documents 2023-01-13 14:36:33 +08:00
dudaodong
2c6e9a3fb9 doc: format document 2023-01-13 11:01:22 +08:00
dudaodong
5f2c3edff4 doc: format document 2023-01-13 10:57:40 +08:00
dudaodong
b422d98702 doc: format document 2023-01-13 10:48:21 +08:00
dudaodong
6f27e0bfbf doc: format document 2023-01-13 10:47:47 +08:00
dudaodong
ce3b6b461e doc: format document 2023-01-13 10:43:16 +08:00
dudaodong
0d6ad4f0d2 doc: format document 2023-01-13 10:41:47 +08:00
dudaodong
c875a7f8b8 doc: format document 2023-01-13 10:39:39 +08:00
dudaodong
0c62d117a1 doc: format document 2023-01-13 10:12:37 +08:00
dudaodong
c260ce493d doc: normalize documents 2023-01-12 15:44:34 +08:00
dudaodong
9ffe96d3ef update readme file 2023-01-12 11:32:43 +08:00
dudaodong
d4bba76dc8 fix: fix ExampleSchedule failed 2023-01-09 11:25:14 +08:00
dudaodong
adaa3ebc43 Merge branch 'main' into v2 2023-01-09 11:16:13 +08:00
dudaodong
61d38ae3b8 doc: update doc for algorithm package 2023-01-09 11:15:25 +08:00
dudaodong
c85d910044 add playground demo 2023-01-09 11:02:41 +08:00
33 changed files with 4324 additions and 3281 deletions

View File

@@ -1,5 +1,5 @@
<div align=center> <div align=center>
<a href="https://uvdream.github.io/lancet-docs/en/"><img src="./logo.png" width="200" height="200"/></a> <img src="./logo.png" width="200" height="200"/>
<br/> <br/>
@@ -113,6 +113,7 @@ import "github.com/duke-git/lancet/v2/algorithm"
[[play](https://go.dev/play/p/Anozfr8ZLH3)] [[play](https://go.dev/play/p/Anozfr8ZLH3)]
- **<big>LinearSearch</big>** : returns the index of target in slice base on equal function. - **<big>LinearSearch</big>** : returns the index of target in slice base on equal function.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/algorithm.md#LinearSearch)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/algorithm.md#LinearSearch)]
[[play](https://go.dev/play/p/IsS7rgn5s3x)]
- **<big>LRUCache</big>** : implements memory cache with lru algorithm. - **<big>LRUCache</big>** : implements memory cache with lru algorithm.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/algorithm.md#LRUCache)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/algorithm.md#LRUCache)]
[[play](https://go.dev/play/p/-EZjgOURufP)] [[play](https://go.dev/play/p/-EZjgOURufP)]
@@ -127,24 +128,34 @@ import "github.com/duke-git/lancet/v2/concurrency"
- **<big>NewChannel</big>** : create a Channel pointer instance. - **<big>NewChannel</big>** : create a Channel pointer instance.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#NewChannel)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#NewChannel)]
[[play](https://go.dev/play/p/7aB4KyMMp9A)]
- **<big>Bridge</big>** : link multiply channels into one channel. - **<big>Bridge</big>** : link multiply channels into one channel.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/Bridge.md#NewChannel)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/Bridge.md#NewChannel)]
[[play](https://go.dev/play/p/qmWSy1NVF-Y)]
- **<big>FanIn</big>** : merge multiple channels into one channel. - **<big>FanIn</big>** : merge multiple channels into one channel.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#FanIn)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#FanIn)]
[[play](https://go.dev/play/p/2VYFMexEvTm)]
- **<big>Generate</big>** : creates a channel, then put values into the channel. - **<big>Generate</big>** : creates a channel, then put values into the channel.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#Generate)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#Generate)]
[[play](https://go.dev/play/p/7aB4KyMMp9A)]
- **<big>Or</big>** : read one or more channels into one channel, will close when any readin channel is closed. - **<big>Or</big>** : read one or more channels into one channel, will close when any readin channel is closed.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#Or)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#Or)]
[[play](https://go.dev/play/p/Wqz9rwioPww)]
- **<big>OrDone</big>** : read a channel into another channel, will close until cancel context. - **<big>OrDone</big>** : read a channel into another channel, will close until cancel context.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#OrDone)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#OrDone)]
[[play](https://go.dev/play/p/lm_GoS6aDjo)]
- **<big>Repeat</big>** : create channel, put values into the channel repeatly until cancel the context. - **<big>Repeat</big>** : create channel, put values into the channel repeatly until cancel the context.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#Repeat)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#Repeat)]
[[play](https://go.dev/play/p/k5N_ALVmYjE)]
- **<big>RepeatFn</big>** : create a channel, excutes fn repeatly, and put the result into the channel, until close context. - **<big>RepeatFn</big>** : create a channel, excutes fn repeatly, and put the result into the channel, until close context.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#RepeatFn)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#RepeatFn)]
[[play](https://go.dev/play/p/4J1zAWttP85)]
- **<big>Take</big>** : create a channel whose values are taken from another channel with limit number. - **<big>Take</big>** : create a channel whose values are taken from another channel with limit number.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#Take)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#Take)]
[[play](https://go.dev/play/p/9Utt-1pDr2J)]
- **<big>Tee</big>** : split one chanel into two channels, until cancel the context. - **<big>Tee</big>** : split one chanel into two channels, until cancel the context.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency.md#Tee)] [[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... ### 3. Condition package contains some functions for conditional judgment. eg. And, Or, TernaryOperator...
@@ -556,8 +567,10 @@ import "github.com/duke-git/lancet/v2/function"
[[play](https://go.dev/play/p/0HqUDIFZ3IL)] [[play](https://go.dev/play/p/0HqUDIFZ3IL)]
- **<big>CurryFn</big>** : make a curry function. - **<big>CurryFn</big>** : make a curry function.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/function.md#CurryFn)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/function.md#CurryFn)]
[[play](https://go.dev/play/p/5HopfDwANKX)]
- **<big>Compose</big>** : compose the functions from right to left. - **<big>Compose</big>** : compose the functions from right to left.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/function.md#Compose)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/function.md#Compose)]
[[play](https://go.dev/play/p/KKfugD4PKYF)]
- **<big>Delay</big>** : call the function after delayed time. - **<big>Delay</big>** : call the function after delayed time.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/function.md#Delay)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/function.md#Delay)]
[[play](https://go.dev/play/p/Ivtc2ZE-Tye)] [[play](https://go.dev/play/p/Ivtc2ZE-Tye)]
@@ -572,6 +585,8 @@ import "github.com/duke-git/lancet/v2/function"
[[play](https://go.dev/play/p/mPdUVvj6HD6)] [[play](https://go.dev/play/p/mPdUVvj6HD6)]
- **<big>Watcher</big>** : Watcher is used for record code excution time. can start/stop/reset the watch timer. get the elapsed time of function execution. - **<big>Watcher</big>** : Watcher is used for record code excution time. can start/stop/reset the watch timer. get the elapsed time of function execution.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/function.md#Watcher)] [[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. ### 11. Maputil package includes some functions to manipulate map.
@@ -640,6 +655,7 @@ import "github.com/duke-git/lancet/v2/mathutil"
[[play](https://go.dev/play/p/N9qgYg_Ho6f)] [[play](https://go.dev/play/p/N9qgYg_Ho6f)]
- **<big>Percent</big>** : calculate the percentage of value to total. - **<big>Percent</big>** : calculate the percentage of value to total.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#Percent)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#Percent)]
[[play](https://go.dev/play/p/QQM9B13coSP)]
- **<big>RoundToFloat</big>** : round up to n decimal places for float64. - **<big>RoundToFloat</big>** : round up to n decimal places for float64.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#RoundToFloat)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil.md#RoundToFloat)]
[[play](https://go.dev/play/p/ghyb528JRJL)] [[play](https://go.dev/play/p/ghyb528JRJL)]
@@ -1000,6 +1016,7 @@ import "github.com/duke-git/lancet/v2/strutil"
[[play](https://go.dev/play/p/Us-ySSbWh-3)] [[play](https://go.dev/play/p/Us-ySSbWh-3)]
- **<big>Substring</big>** : returns a substring of the specific length starting at the specific offset position. - **<big>Substring</big>** : returns a substring of the specific length starting at the specific offset position.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#Substring)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#Substring)]
[[play](https://go.dev/play/p/q3sM6ehnPDp)]
- **<big>Wrap</big>** : wrap a string with given string. - **<big>Wrap</big>** : wrap a string with given string.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#Wrap)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#Wrap)]
[[play](https://go.dev/play/p/KoZOlZDDt9y)] [[play](https://go.dev/play/p/KoZOlZDDt9y)]

View File

@@ -1,5 +1,5 @@
<div align=center> <div align=center>
<a href="https://uvdream.github.io/lancet-docs/"><img src="./logo.png" width="200" height="200"/><a/> <img src="./logo.png" width="200" height="200"/>
<br/> <br/>
@@ -112,6 +112,7 @@ import "github.com/duke-git/lancet/v2/algorithm"
[[play](https://go.dev/play/p/Anozfr8ZLH3)] [[play](https://go.dev/play/p/Anozfr8ZLH3)]
- **<big>LinearSearch</big>** : 基于传入的相等函数返回切片中目标值的索引。(线性查找) - **<big>LinearSearch</big>** : 基于传入的相等函数返回切片中目标值的索引。(线性查找)
[[doc](https://github.com/duke-git/lancet/blob/main/docs/algorithm_zh-CN.md#LinearSearch)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/algorithm_zh-CN.md#LinearSearch)]
[[play](https://go.dev/play/p/IsS7rgn5s3x)]
- **<big>LRUCache</big>** : 应用 lru 算法实现内存缓存. - **<big>LRUCache</big>** : 应用 lru 算法实现内存缓存.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/algorithm_zh-CN.md#LRUCache)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/algorithm_zh-CN.md#LRUCache)]
[[play](https://go.dev/play/p/-EZjgOURufP)] [[play](https://go.dev/play/p/-EZjgOURufP)]
@@ -126,24 +127,34 @@ import "github.com/duke-git/lancet/v2/concurrency"
- **<big>NewChannel</big>** : 返回一个 Channel 指针实例。 - **<big>NewChannel</big>** : 返回一个 Channel 指针实例。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#NewChannel)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#NewChannel)]
[[play](https://go.dev/play/p/7aB4KyMMp9A)]
- **<big>Bridge</big>** : 将多个 channel 链接到一个 channel直到取消上下文。 - **<big>Bridge</big>** : 将多个 channel 链接到一个 channel直到取消上下文。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/Bridge.md#NewChannel)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/Bridge.md#NewChannel)]
[[play](https://go.dev/play/p/qmWSy1NVF-Y)]
- **<big>FanIn</big>** : 将多个 channel 合并为一个 channel直到取消上下文。 - **<big>FanIn</big>** : 将多个 channel 合并为一个 channel直到取消上下文。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#FanIn)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#FanIn)]
[[play](https://go.dev/play/p/2VYFMexEvTm)]
- **<big>Generate</big>** : 根据传入的值,生成 channel。 - **<big>Generate</big>** : 根据传入的值,生成 channel。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#Generate)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#Generate)]
[[play](https://go.dev/play/p/7aB4KyMMp9A)]
- **<big>Or</big>** : 将一个或多个 channel 读取到一个 channel 中,当任何读取 channel 关闭时将结束读取。 - **<big>Or</big>** : 将一个或多个 channel 读取到一个 channel 中,当任何读取 channel 关闭时将结束读取。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#Or)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#Or)]
[[play](https://go.dev/play/p/Wqz9rwioPww)]
- **<big>OrDone</big>** : 将一个 channel 读入另一个 channel直到取消上下文。 - **<big>OrDone</big>** : 将一个 channel 读入另一个 channel直到取消上下文。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#OrDone)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#OrDone)]
[[play](https://go.dev/play/p/lm_GoS6aDjo)]
- **<big>Repeat</big>** : 返回一个 channel将参数`values`重复放入 channel直到取消上下文。 - **<big>Repeat</big>** : 返回一个 channel将参数`values`重复放入 channel直到取消上下文。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#Repeat)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#Repeat)]
[[play](https://go.dev/play/p/k5N_ALVmYjE)]
- **<big>RepeatFn</big>** : 返回一个 channel重复执行函数 fn并将结果放入返回的 channel直到取消上下文。 - **<big>RepeatFn</big>** : 返回一个 channel重复执行函数 fn并将结果放入返回的 channel直到取消上下文。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#RepeatFn)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#RepeatFn)]
[[play](https://go.dev/play/p/4J1zAWttP85)]
- **<big>Take</big>** : 返回一个 channel其值从另一个 channel 获取,直到取消上下文。 - **<big>Take</big>** : 返回一个 channel其值从另一个 channel 获取,直到取消上下文。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#Take)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#Take)]
[[play](https://go.dev/play/p/9Utt-1pDr2J)]
- **<big>Tee</big>** : 将一个 channel 分成两个 channel直到取消上下文。 - **<big>Tee</big>** : 将一个 channel 分成两个 channel直到取消上下文。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#Tee)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/concurrency_zh-CN.md#Tee)]
[[play](https://go.dev/play/p/3TQPKnCirrP)]
### 3. condition 包含一些用于条件判断的函数。 ### 3. condition 包含一些用于条件判断的函数。
@@ -559,8 +570,10 @@ import "github.com/duke-git/lancet/v2/function"
[[play](https://go.dev/play/p/0HqUDIFZ3IL)] [[play](https://go.dev/play/p/0HqUDIFZ3IL)]
- **<big>CurryFn</big>** : 创建柯里化函数。 - **<big>CurryFn</big>** : 创建柯里化函数。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/function_zh-CN.md#CurryFn)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/function_zh-CN.md#CurryFn)]
[[play](https://go.dev/play/p/5HopfDwANKX)]
- **<big>Compose</big>** : 从右至左组合函数列表fnList返回组合后的函数。 - **<big>Compose</big>** : 从右至左组合函数列表fnList返回组合后的函数。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/function_zh-CN.md#Compose)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/function_zh-CN.md#Compose)]
[[play](https://go.dev/play/p/KKfugD4PKYF)]
- **<big>Delay</big>** : 延迟delay时间后调用函数。 - **<big>Delay</big>** : 延迟delay时间后调用函数。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/function_zh-CN.md#Delay)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/function_zh-CN.md#Delay)]
[[play](https://go.dev/play/p/Ivtc2ZE-Tye)] [[play](https://go.dev/play/p/Ivtc2ZE-Tye)]
@@ -575,6 +588,7 @@ import "github.com/duke-git/lancet/v2/function"
[[play](https://go.dev/play/p/mPdUVvj6HD6)] [[play](https://go.dev/play/p/mPdUVvj6HD6)]
- **<big>Watcher</big>** : Watcher用于记录代码执行时间。可以启动/停止/重置手表定时器。获取函数执行的时间。 - **<big>Watcher</big>** : Watcher用于记录代码执行时间。可以启动/停止/重置手表定时器。获取函数执行的时间。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/function_zh-CN.md#Watcher)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/function_zh-CN.md#Watcher)]
[[play](https://go.dev/play/p/l2yrOpCLd1I)]
### 11. maputil 包括一些操作 map 的函数. ### 11. maputil 包括一些操作 map 的函数.
@@ -644,6 +658,7 @@ import "github.com/duke-git/lancet/v2/mathutil"
[[play](https://go.dev/play/p/N9qgYg_Ho6f)] [[play](https://go.dev/play/p/N9qgYg_Ho6f)]
- **<big>Percent</big>** : 计算百分比,可以指定保留 n 位小数。 - **<big>Percent</big>** : 计算百分比,可以指定保留 n 位小数。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil_zh-CN.md#Percent)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil_zh-CN.md#Percent)]
[[play](https://go.dev/play/p/QQM9B13coSP)]
- **<big>RoundToFloat</big>** : 四舍五入,保留 n 位小数,返回 float64。 - **<big>RoundToFloat</big>** : 四舍五入,保留 n 位小数,返回 float64。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil_zh-CN.md#RoundToFloat)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/mathutil_zh-CN.md#RoundToFloat)]
[[play](https://go.dev/play/p/ghyb528JRJL)] [[play](https://go.dev/play/p/ghyb528JRJL)]
@@ -1010,6 +1025,7 @@ import "github.com/duke-git/lancet/v2/strutil"
[[play](https://go.dev/play/p/Us-ySSbWh-3)] [[play](https://go.dev/play/p/Us-ySSbWh-3)]
- **<big>Substring</big>** : 根据指定的位置和长度截取子字符串。 - **<big>Substring</big>** : 根据指定的位置和长度截取子字符串。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#Substring)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil.md#Substring)]
[[play](https://go.dev/play/p/q3sM6ehnPDp)]
- **<big>Wrap</big>** : 用给定字符包裹传入的字符串 - **<big>Wrap</big>** : 用给定字符包裹传入的字符串
[[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil_zh-CN.md#Wrap)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/strutil_zh-CN.md#Wrap)]
[[play](https://go.dev/play/p/KoZOlZDDt9y)] [[play](https://go.dev/play/p/KoZOlZDDt9y)]
@@ -1160,7 +1176,6 @@ import "github.com/duke-git/lancet/v2/xerror"
[[doc](https://github.com/duke-git/lancet/blob/main/docs/xerror_zh-CN.md#Unwrap)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/xerror_zh-CN.md#Unwrap)]
[[play](https://go.dev/play/p/w84d7Mb3Afk)] [[play](https://go.dev/play/p/w84d7Mb3Afk)]
- [Unwrap](https://github.com/duke-git/lancet/blob/main/docs/xerror_zh-CN.md#Unwrap)
## 如何贡献代码 ## 如何贡献代码

View File

@@ -10,7 +10,7 @@ import "github.com/duke-git/lancet/v2/lancetconstraints"
// LinearSearch return the index of target in slice base on equal function. // LinearSearch return the index of target in slice base on equal function.
// If not found return -1 // If not found return -1
// Play: Todo // Play: https://go.dev/play/p/IsS7rgn5s3x
func LinearSearch[T any](slice []T, target T, equal func(a, b T) bool) int { func LinearSearch[T any](slice []T, target T, equal func(a, b T) bool) int {
for i, v := range slice { for i, v := range slice {
if equal(v, target) { if equal(v, target) {

View File

@@ -20,7 +20,7 @@ func NewChannel[T any]() *Channel[T] {
} }
// Generate creates channel, then put values into the channel. // Generate creates channel, then put values into the channel.
// Play: Todo // Play: https://go.dev/play/p/7aB4KyMMp9A
func (c *Channel[T]) Generate(ctx context.Context, values ...T) <-chan T { func (c *Channel[T]) Generate(ctx context.Context, values ...T) <-chan T {
dataStream := make(chan T) dataStream := make(chan T)
@@ -40,7 +40,7 @@ func (c *Channel[T]) Generate(ctx context.Context, values ...T) <-chan T {
} }
// Repeat create channel, put values into the channel repeatly until cancel the context. // Repeat create channel, put values into the channel repeatly until cancel the context.
// Play: Todo // Play: https://go.dev/play/p/k5N_ALVmYjE
func (c *Channel[T]) Repeat(ctx context.Context, values ...T) <-chan T { func (c *Channel[T]) Repeat(ctx context.Context, values ...T) <-chan T {
dataStream := make(chan T) dataStream := make(chan T)
@@ -61,7 +61,7 @@ func (c *Channel[T]) Repeat(ctx context.Context, values ...T) <-chan T {
// RepeatFn create a channel, excutes fn repeatly, and put the result into the channel // RepeatFn create a channel, excutes fn repeatly, and put the result into the channel
// until close context. // until close context.
// Play: Todo // Play: https://go.dev/play/p/4J1zAWttP85
func (c *Channel[T]) RepeatFn(ctx context.Context, fn func() T) <-chan T { func (c *Channel[T]) RepeatFn(ctx context.Context, fn func() T) <-chan T {
dataStream := make(chan T) dataStream := make(chan T)
@@ -79,7 +79,7 @@ func (c *Channel[T]) RepeatFn(ctx context.Context, fn func() T) <-chan T {
} }
// Take create a channel whose values are taken from another channel with limit number. // Take create a channel whose values are taken from another channel with limit number.
// Play: Todo // Play: https://go.dev/play/p/9Utt-1pDr2J
func (c *Channel[T]) Take(ctx context.Context, valueStream <-chan T, number int) <-chan T { func (c *Channel[T]) Take(ctx context.Context, valueStream <-chan T, number int) <-chan T {
takeStream := make(chan T) takeStream := make(chan T)
@@ -99,7 +99,7 @@ func (c *Channel[T]) Take(ctx context.Context, valueStream <-chan T, number int)
} }
// FanIn merge multiple channels into one channel. // FanIn merge multiple channels into one channel.
// Play: Todo // Play: https://go.dev/play/p/2VYFMexEvTm
func (c *Channel[T]) FanIn(ctx context.Context, channels ...<-chan T) <-chan T { func (c *Channel[T]) FanIn(ctx context.Context, channels ...<-chan T) <-chan T {
out := make(chan T) out := make(chan T)
@@ -127,7 +127,7 @@ func (c *Channel[T]) FanIn(ctx context.Context, channels ...<-chan T) <-chan T {
} }
// Tee split one chanel into two channels, until cancel the context. // Tee split one chanel into two channels, until cancel the context.
// Play: Todo // Play: https://go.dev/play/p/3TQPKnCirrP
func (c *Channel[T]) Tee(ctx context.Context, in <-chan T) (<-chan T, <-chan T) { func (c *Channel[T]) Tee(ctx context.Context, in <-chan T) (<-chan T, <-chan T) {
out1 := make(chan T) out1 := make(chan T)
out2 := make(chan T) out2 := make(chan T)
@@ -154,7 +154,7 @@ func (c *Channel[T]) Tee(ctx context.Context, in <-chan T) (<-chan T, <-chan T)
} }
// Bridge link multiply channels into one channel. // Bridge link multiply channels into one channel.
// Play: Todo // Play: https://go.dev/play/p/qmWSy1NVF-Y
func (c *Channel[T]) Bridge(ctx context.Context, chanStream <-chan <-chan T) <-chan T { func (c *Channel[T]) Bridge(ctx context.Context, chanStream <-chan <-chan T) <-chan T {
valStream := make(chan T) valStream := make(chan T)
@@ -186,7 +186,7 @@ func (c *Channel[T]) Bridge(ctx context.Context, chanStream <-chan <-chan T) <-c
} }
// Or read one or more channels into one channel, will close when any readin channel is closed. // Or read one or more channels into one channel, will close when any readin channel is closed.
// Play: Todo // Play: https://go.dev/play/p/Wqz9rwioPww
func (c *Channel[T]) Or(channels ...<-chan T) <-chan T { func (c *Channel[T]) Or(channels ...<-chan T) <-chan T {
switch len(channels) { switch len(channels) {
case 0: case 0:
@@ -220,7 +220,7 @@ func (c *Channel[T]) Or(channels ...<-chan T) <-chan T {
} }
// OrDone read a channel into another channel, will close until cancel context. // OrDone read a channel into another channel, will close until cancel context.
// Play: Todo // Play: https://go.dev/play/p/lm_GoS6aDjo
func (c *Channel[T]) OrDone(ctx context.Context, channel <-chan T) <-chan T { func (c *Channel[T]) OrDone(ctx context.Context, channel <-chan T) <-chan T {
valStream := make(chan T) valStream := make(chan T)

View File

@@ -1,17 +1,19 @@
# Algorithm # Algorithm
Package algorithm implements some basic algorithm. eg. sort, search. Package algorithm implements some basic algorithm. eg. sort, search.
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Source ## Source
- [https://github.com/duke-git/lancet/blob/main/algorithm/sort.go](https://github.com/duke-git/lancet/blob/main/algorithm/sort.go) - [https://github.com/duke-git/lancet/blob/main/algorithm/sort.go](https://github.com/duke-git/lancet/blob/main/algorithm/sort.go)
- [https://github.com/duke-git/lancet/blob/main/algorithm/search.go](https://github.com/duke-git/lancet/blob/main/algorithm/search.go) - [https://github.com/duke-git/lancet/blob/main/algorithm/search.go](https://github.com/duke-git/lancet/blob/main/algorithm/search.go)
- [https://github.com/duke-git/lancet/blob/main/algorithm/lru_cache.go](https://github.com/duke-git/lancet/blob/main/algorithm/lru_cache.go) - [https://github.com/duke-git/lancet/blob/main/algorithm/lru_cache.go](https://github.com/duke-git/lancet/blob/main/algorithm/lru_cache.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Usage ## Usage
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
@@ -22,27 +24,25 @@ import (
## Index ## Index
- [BubbleSort](#BubbleSort) - [BubbleSort](#BubbleSort)
- [InsertionSort](#InsertionSort) - [InsertionSort](#InsertionSort)
- [SelectionSort](#SelectionSort) - [SelectionSort](#SelectionSort)
- [ShellSort](#ShellSort) - [ShellSort](#ShellSort)
- [QuickSort](#QuickSort) - [QuickSort](#QuickSort)
- [HeapSort](#HeapSort) - [HeapSort](#HeapSort)
- [MergeSort](#MergeSort) - [MergeSort](#MergeSort)
- [CountSort](#CountSort) - [CountSort](#CountSort)
- [BinarySearch](#BinarySearch) - [BinarySearch](#BinarySearch)
- [BinaryIterativeSearch](#BinaryIterativeSearch) - [BinaryIterativeSearch](#BinaryIterativeSearch)
- [LinearSearch](#LinearSearch) - [LinearSearch](#LinearSearch)
- [LRUCache](#LRUCache) - [LRUCache](#LRUCache)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Documentation ## Documentation
### <span id="BubbleSort">BubbleSort</span> ### <span id="BubbleSort">BubbleSort</span>
<p>Sort slice with bubble sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p> <p>Sort slice with bubble sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -50,6 +50,7 @@ import (
```go ```go
func BubbleSort[T any](slice []T, comparator lancetconstraints.Comparator) func BubbleSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -60,34 +61,36 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.BubbleSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.BubbleSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="InsertionSort">InsertionSort</span> ### <span id="InsertionSort">InsertionSort</span>
<p>Sort slice with insertion sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p> <p>Sort slice with insertion sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -95,6 +98,7 @@ func main() {
```go ```go
func InsertionSort[T any](slice []T, comparator lancetconstraints.Comparator) func InsertionSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -105,54 +109,51 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
type people struct {
Name string
Age int
}
// PeopleAageComparator sort people slice by age field
type peopleAgeComparator struct{}
// Compare implements github.com/duke-git/lancet/lancetconstraints/constraints.go/Comparator
func (pc *peopleAgeComparator) Compare(v1 any, v2 any) int {
p1, _ := v1.(people)
p2, _ := v2.(people)
//ascending order
if p1.Age < p2.Age {
return -1
} else if p1.Age > p2.Age {
return 1
}
return 0
}
func main() { func main() {
type people struct { peoples := []people{
Name string
Age int
}
// PeopleAageComparator sort people slice by age field
type peopleAgeComparator struct{}
// Compare implements github.com/duke-git/lancet/lancetconstraints/constraints.go/Comparator
func (pc *peopleAgeComparator) Compare(v1 any, v2 any) int {
p1, _ := v1.(people)
p2, _ := v2.(people)
//ascending order
if p1.Age < p2.Age {
return -1
} else if p1.Age > p2.Age {
return 1
}
return 0
//decending order
// if p1.Age > p2.Age {
// return -1
// } else if p1.Age < p2.Age {
// return 1
// }
}
var peoples = []people{
{Name: "a", Age: 20}, {Name: "a", Age: 20},
{Name: "b", Age: 10}, {Name: "b", Age: 10},
{Name: "c", Age: 17}, {Name: "c", Age: 17},
{Name: "d", Age: 8}, {Name: "d", Age: 8},
{Name: "e", Age: 28}, {Name: "e", Age: 28},
} }
comparator := &peopleAgeComparator{} comparator := &peopleAgeComparator{}
algorithm.InsertionSort(peoples, comparator) algorithm.InsertionSort(peoples, comparator)
fmt.Println(peoples) //[{d 8} {b 10} {c 17} {a 20} {e 28}] fmt.Println(peoples)
// Output:
// [{d 8} {b 10} {c 17} {a 20} {e 28}]
} }
``` ```
### <span id="SelectionSort">SelectionSort</span> ### <span id="SelectionSort">SelectionSort</span>
<p>Sort slice with selection sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p> <p>Sort slice with selection sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -160,6 +161,7 @@ func main() {
```go ```go
func SelectionSort[T any](slice []T, comparator lancetconstraints.Comparator) func SelectionSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -170,34 +172,36 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.SelectionSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.SelectionSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="ShellSort">ShellSort</span> ### <span id="ShellSort">ShellSort</span>
<p>Sort slice with shell sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p> <p>Sort slice with shell sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -205,6 +209,7 @@ func main() {
```go ```go
func ShellSort[T any](slice []T, comparator lancetconstraints.Comparator) func ShellSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -215,34 +220,36 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.ShellSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.ShellSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="QuickSort">QuickSort</span> ### <span id="QuickSort">QuickSort</span>
<p>Sort slice with quick sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p> <p>Sort slice with quick sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -250,6 +257,7 @@ func main() {
```go ```go
func QuickSort[T any](slice []T comparator lancetconstraints.Comparator) func QuickSort[T any](slice []T comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -260,34 +268,36 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.QuickSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.QuickSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="HeapSort">HeapSort</span> ### <span id="HeapSort">HeapSort</span>
<p>Sort slice with heap sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p> <p>Sort slice with heap sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -295,6 +305,7 @@ func main() {
```go ```go
func HeapSort[T any](slice []T, comparator lancetconstraints.Comparator) func HeapSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -305,34 +316,36 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.HeapSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.HeapSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="MergeSort">MergeSort</span> ### <span id="MergeSort">MergeSort</span>
<p>Sort slice with merge sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p> <p>Sort slice with merge sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -340,6 +353,7 @@ func main() {
```go ```go
func MergeSort[T any](slice []T, comparator lancetconstraints.Comparator) func MergeSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -350,33 +364,36 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.MergeSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.MergeSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="CountSort">CountSort</span> ### <span id="CountSort">CountSort</span>
<p>Sort slice with count sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p> <p>Sort slice with count sort algorithm. Param comparator should implements lancetconstraints.Comparator.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -384,6 +401,7 @@ func main() {
```go ```go
func CountSort[T any](slice []T, comparator lancetconstraints.Comparator) []T func CountSort[T any](slice []T, comparator lancetconstraints.Comparator) []T
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -394,34 +412,37 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() {
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { type intComparator struct{}
val1, _ := v1.(int)
val2, _ := v2.(int)
//ascending order func (c *intComparator) Compare(v1 any, v2 any) int {
if val1 < val2 { val1, _ := v1.(int)
return -1 val2, _ := v2.(int)
} else if val1 > val2 {
return 1 //ascending order
} if val1 < val2 {
return 0 return -1
} else if val1 > val2 {
return 1
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
sortedSlice := algorithm.CountSort(intSlice, comparator)
fmt.Println(sortedSlice) //[]int{1, 2, 3, 4, 5, 6} sortedNums := algorithm.CountSort(numbers, comparator)
fmt.Println(sortedNums)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="BinarySearch">BinarySearch</span> ### <span id="BinarySearch">BinarySearch</span>
<p>BinarySearch search for target within a sorted slice, recursive call itself. If a target is found, the index of the target is returned. Else the function return -1.</p> <p>BinarySearch search for target within a sorted slice, recursive call itself. If a target is found, the index of the target is returned. Else the function return -1.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -429,6 +450,7 @@ func main() {
```go ```go
func BinarySearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) int func BinarySearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) int
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -439,35 +461,39 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
var sortedNumbers = []int{1, 2, 3, 4, 5, 6, 7, 8} func main() {
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8}
comparator := &intComparator{} comparator := &intComparator{}
foundIndex := algorithm.BinarySearch(sortedNumbers, 5, 0, len(sortedNumbers)-1, comparator)
fmt.Println(foundIndex) //4
notFoundIndex := algorithm.BinarySearch(sortedNumbers, 9, 0, len(sortedNumbers)-1, comparator) result1 := algorithm.BinarySearch(numbers, 5, 0, len(numbers)-1, comparator)
fmt.Println(notFoundIndex) //-1 result2 := algorithm.BinarySearch(numbers, 9, 0, len(numbers)-1, comparator)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 4
// -1
} }
``` ```
### <span id="BinaryIterativeSearch">BinaryIterativeSearch</span> ### <span id="BinaryIterativeSearch">BinaryIterativeSearch</span>
<p>BinaryIterativeSearch search for target within a sorted slice, recursive call itself. If a target is found, the index of the target is returned. Else the function return -1.</p> <p>BinaryIterativeSearch search for target within a sorted slice, recursive call itself. If a target is found, the index of the target is returned. Else the function return -1.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -475,6 +501,7 @@ func main() {
```go ```go
func BinaryIterativeSearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) int func BinaryIterativeSearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) int
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -485,43 +512,47 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
var sortedNumbers = []int{1, 2, 3, 4, 5, 6, 7, 8} func main() {
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8}
comparator := &intComparator{} comparator := &intComparator{}
foundIndex := algorithm.BinaryIterativeSearch(sortedNumbers, 5, 0, len(sortedNumbers)-1, comparator)
fmt.Println(foundIndex) //4
notFoundIndex := algorithm.BinaryIterativeSearch(sortedNumbers, 9, 0, len(sortedNumbers)-1, comparator) result1 := algorithm.BinaryIterativeSearch(numbers, 5, 0, len(numbers)-1, comparator)
fmt.Println(notFoundIndex) //-1 result2 := algorithm.BinaryIterativeSearch(numbers, 9, 0, len(numbers)-1, comparator)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 4
// -1
} }
``` ```
### <span id="LinearSearch">LinearSearch</span> ### <span id="LinearSearch">LinearSearch</span>
<p>LinearSearch Simple linear search algorithm that iterates over all elements of an slice. If a target is found, the index of the target is returned. Else the function return -1.</p>
<p>return the index of target in slice base on equal function.If a target is found, the index of the target is returned. Else the function return -1.</p>
<b>Signature:</b> <b>Signature:</b>
```go ```go
func LinearSearch[T any](slice []T, target T, comparator lancetconstraints.Comparator) int func LinearSearch[T any](slice []T, target T, equal func(a, b T) bool) int
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -533,35 +564,26 @@ import (
) )
func main() { func main() {
type intComparator struct{} numbers := []int{3, 4, 5, 3, 2, 1}
func (c *intComparator) Compare(v1 any, v2 any) int { equalFunc := func(a, b int) bool {
val1, _ := v1.(int) return a == b
val2, _ := v2.(int)
//ascending order
if val1 < val2 {
return -1
} else if val1 > val2 {
return 1
}
return 0
} }
intSlice := []int{2, 1, 5, 3, 6, 4} result1 := algorithm.LinearSearch(numbers, 3, equalFunc)
comparator := &intComparator{} result2 := algorithm.LinearSearch(numbers, 6, equalFunc)
foundIndex := algorithm.LinearSearch(intSlice, 5, comparator)
fmt.Println(foundIndex) //2
notFoundIndex := algorithm.LinearSearch(sortedNumbers, 0, comparator) fmt.Println(result1)
fmt.Println(notFoundIndex) //-1 fmt.Println(result2)
// Output:
// 0
// -1
} }
``` ```
### <span id="LRUCache">LRUCache</span> ### <span id="LRUCache">LRUCache</span>
<p>LRUCache implements mem cache with lru.</p> <p>LRUCache implements mem cache with lru.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -573,6 +595,7 @@ func (l *LRUCache[K, V]) Put(key K, value V)
func (l *LRUCache[K, V]) Delete(key K) bool func (l *LRUCache[K, V]) Delete(key K) bool
func (l *LRUCache[K, V]) Len() int func (l *LRUCache[K, V]) Len() int
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -588,14 +611,26 @@ func main() {
cache.Put(1, 1) cache.Put(1, 1)
cache.Put(2, 2) cache.Put(2, 2)
cache.Put(3, 3)
fmt.Println(cache.Len()) // 3 result1, ok1 := cache.Get(1)
result2, ok2 := cache.Get(2)
result3, ok3 := cache.Get(3)
v, ok := cache.Get(1) fmt.Println(result1, ok1)
fmt.Println(v, ok) // 1 true fmt.Println(result2, ok2)
fmt.Println(result3, ok3)
ok = cache.Delete(1) fmt.Println(cache.Len())
fmt.Println(ok) // true
ok := cache.Delete(2)
fmt.Println(ok)
// Output:
// 1 true
// 2 true
// 0 false
// 2
// true
} }
``` ```

View File

@@ -1,17 +1,19 @@
# Algorithm # Algorithm
algorithm算法包实现一些基本算法sortsearchlrucache。
algorithm 算法包实现一些基本算法sortsearchlrucache。
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 源码 ## 源码
- [https://github.com/duke-git/lancet/blob/main/algorithm/sort.go](https://github.com/duke-git/lancet/blob/main/algorithm/sort.go) - [https://github.com/duke-git/lancet/blob/main/algorithm/sort.go](https://github.com/duke-git/lancet/blob/main/algorithm/sort.go)
- [https://github.com/duke-git/lancet/blob/main/algorithm/search.go](https://github.com/duke-git/lancet/blob/main/algorithm/search.go) - [https://github.com/duke-git/lancet/blob/main/algorithm/search.go](https://github.com/duke-git/lancet/blob/main/algorithm/search.go)
- [https://github.com/duke-git/lancet/blob/main/algorithm/lru_cache.go](https://github.com/duke-git/lancet/blob/main/algorithm/lru_cache.go) - [https://github.com/duke-git/lancet/blob/main/algorithm/lru_cache.go](https://github.com/duke-git/lancet/blob/main/algorithm/lru_cache.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 用法 ## 用法
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
@@ -22,35 +24,34 @@ import (
## 目录 ## 目录
- [BubbleSort](#BubbleSort) - [BubbleSort](#BubbleSort)
- [InsertionSort](#InsertionSort) - [InsertionSort](#InsertionSort)
- [SelectionSort](#SelectionSort) - [SelectionSort](#SelectionSort)
- [ShellSort](#ShellSort) - [ShellSort](#ShellSort)
- [QuickSort](#QuickSort) - [QuickSort](#QuickSort)
- [HeapSort](#HeapSort) - [HeapSort](#HeapSort)
- [MergeSort](#MergeSort) - [MergeSort](#MergeSort)
- [CountSort](#CountSort) - [CountSort](#CountSort)
- [BinarySearch](#BinarySearch) - [BinarySearch](#BinarySearch)
- [BinaryIterativeSearch](#BinaryIterativeSearch) - [BinaryIterativeSearch](#BinaryIterativeSearch)
- [LinearSearch](#LinearSearch) - [LinearSearch](#LinearSearch)
- [LRUCache](#LRUCache) - [LRUCache](#LRUCache)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 文档 ## 文档
### <span id="BubbleSort">BubbleSort</span> ### <span id="BubbleSort">BubbleSort</span>
<p>冒泡排序参数comparator需要实现包lancetconstraints.Comparator</p>
<p>冒泡排序参数comparator需要实现包lancetconstraints.Comparator。</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func BubbleSort[T any](slice []T, comparator lancetconstraints.Comparator) func BubbleSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -60,42 +61,45 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.BubbleSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.BubbleSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="InsertionSort">InsertionSort</span> ### <span id="InsertionSort">InsertionSort</span>
<p>插入排序参数comparator需要实现包lancetconstraints.Comparator</p>
<p>插入排序参数comparator需要实现包lancetconstraints.Comparator。</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func InsertionSort[T any](slice []T, comparator lancetconstraints.Comparator) func InsertionSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -105,62 +109,60 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
type people struct {
Name string
Age int
}
// PeopleAageComparator sort people slice by age field
type peopleAgeComparator struct{}
// Compare implements github.com/duke-git/lancet/lancetconstraints/constraints.go/Comparator
func (pc *peopleAgeComparator) Compare(v1 any, v2 any) int {
p1, _ := v1.(people)
p2, _ := v2.(people)
//ascending order
if p1.Age < p2.Age {
return -1
} else if p1.Age > p2.Age {
return 1
}
return 0
}
func main() { func main() {
type people struct { peoples := []people{
Name string
Age int
}
// PeopleAageComparator sort people slice by age field
type peopleAgeComparator struct{}
// Compare implements github.com/duke-git/lancet/lancetconstraints/constraints.go/Comparator
func (pc *peopleAgeComparator) Compare(v1 any, v2 any) int {
p1, _ := v1.(people)
p2, _ := v2.(people)
//ascending order
if p1.Age < p2.Age {
return -1
} else if p1.Age > p2.Age {
return 1
}
return 0
//decending order
// if p1.Age > p2.Age {
// return -1
// } else if p1.Age < p2.Age {
// return 1
// }
}
var peoples = []people{
{Name: "a", Age: 20}, {Name: "a", Age: 20},
{Name: "b", Age: 10}, {Name: "b", Age: 10},
{Name: "c", Age: 17}, {Name: "c", Age: 17},
{Name: "d", Age: 8}, {Name: "d", Age: 8},
{Name: "e", Age: 28}, {Name: "e", Age: 28},
} }
comparator := &peopleAgeComparator{} comparator := &peopleAgeComparator{}
algorithm.InsertionSort(peoples, comparator) algorithm.InsertionSort(peoples, comparator)
fmt.Println(intSlice) //[{d 8} {b 10} {c 17} {a 20} {e 28}] fmt.Println(peoples)
// Output:
// [{d 8} {b 10} {c 17} {a 20} {e 28}]
} }
``` ```
### <span id="SelectionSort">SelectionSort</span> ### <span id="SelectionSort">SelectionSort</span>
<p>选择排序参数comparator需要实现包lancetconstraints.Comparator</p>
<p>选择排序参数comparator需要实现包lancetconstraints.Comparator。</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func SelectionSort[T any](slice []T, comparator lancetconstraints.Comparator) func SelectionSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -170,42 +172,45 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.SelectionSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.SelectionSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="ShellSort">ShellSort</span> ### <span id="ShellSort">ShellSort</span>
<p>希尔排序参数comparator需要实现包lancetconstraints.Comparator</p>
<p>希尔排序参数comparator需要实现包lancetconstraints.Comparator。</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ShellSort[T any](slice []T, comparator lancetconstraints.Comparator) func ShellSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -215,42 +220,45 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.ShellSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.ShellSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="QuickSort">QuickSort</span> ### <span id="QuickSort">QuickSort</span>
<p>快速排序参数comparator需要实现包lancetconstraints.Comparator</p>
<p>快速排序参数comparator需要实现包lancetconstraints.Comparator。</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func QuickSort[T any](slice []T, comparator lancetconstraints.Comparator) []T func QuickSort[T any](slice []T comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -260,42 +268,45 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.QuickSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.QuickSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="HeapSort">HeapSort</span> ### <span id="HeapSort">HeapSort</span>
<p>堆排序参数comparator需要实现包lancetconstraints.Comparator</p>
<p>堆排序参数comparator需要实现包lancetconstraints.Comparator。</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func HeapSort[T any](slice []T, comparator lancetconstraints.Comparator) []T func HeapSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -305,42 +316,45 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.HeapSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.HeapSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="MergeSort">MergeSort</span> ### <span id="MergeSort">MergeSort</span>
<p>归并排序参数comparator需要实现包lancetconstraints.Comparator</p>
<p>归并排序参数comparator需要实现包lancetconstraints.Comparator。</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func MergeSort[T any](slice []T, comparator lancetconstraints.Comparator) func MergeSort[T any](slice []T, comparator lancetconstraints.Comparator)
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -350,41 +364,45 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
algorithm.MergeSort(intSlice, comparator)
fmt.Println(intSlice) //[]int{1, 2, 3, 4, 5, 6} algorithm.MergeSort(numbers, comparator)
fmt.Println(numbers)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="CountSort">CountSort</span> ### <span id="CountSort">CountSort</span>
<p>计数排序参数comparator需要实现包lancetconstraints.Comparator</p>
<p>计数排序参数comparator需要实现包lancetconstraints.Comparator。</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func CountSort[T any](slice []T, comparator lancetconstraints.Comparator) []T func CountSort[T any](slice []T, comparator lancetconstraints.Comparator) []T
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -394,42 +412,46 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() {
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { type intComparator struct{}
val1, _ := v1.(int)
val2, _ := v2.(int)
//ascending order func (c *intComparator) Compare(v1 any, v2 any) int {
if val1 < val2 { val1, _ := v1.(int)
return -1 val2, _ := v2.(int)
} else if val1 > val2 {
return 1 //ascending order
} if val1 < val2 {
return 0 return -1
} else if val1 > val2 {
return 1
} }
return 0
}
intSlice := []int{2, 1, 5, 3, 6, 4} func main() {
numbers := []int{2, 1, 5, 3, 6, 4}
comparator := &intComparator{} comparator := &intComparator{}
sortedSlice := algorithm.CountSort(intSlice, comparator)
fmt.Println(sortedSlice) //[]int{1, 2, 3, 4, 5, 6} sortedNums := algorithm.CountSort(numbers, comparator)
fmt.Println(sortedNums)
// Output:
// [1 2 3 4 5 6]
} }
``` ```
### <span id="BinarySearch">BinarySearch</span> ### <span id="BinarySearch">BinarySearch</span>
<p>二分递归查找,返回元素索引,未找到元素返回-1参数comparator需要实现包lancetconstraints.Comparator</p>
<p>二分递归查找,返回元素索引,未找到元素返回-1参数comparator需要实现包lancetconstraints.Comparator。</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func BinarySearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) int func BinarySearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) int
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -439,43 +461,48 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
var sortedNumbers = []int{1, 2, 3, 4, 5, 6, 7, 8} func main() {
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8}
comparator := &intComparator{} comparator := &intComparator{}
foundIndex := algorithm.BinarySearch(sortedNumbers, 5, 0, len(sortedNumbers)-1, comparator)
fmt.Println(foundIndex) //4
notFoundIndex := algorithm.BinarySearch(sortedNumbers, 9, 0, len(sortedNumbers)-1, comparator) result1 := algorithm.BinarySearch(numbers, 5, 0, len(numbers)-1, comparator)
fmt.Println(notFoundIndex) //-1 result2 := algorithm.BinarySearch(numbers, 9, 0, len(numbers)-1, comparator)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 4
// -1
} }
``` ```
### <span id="BinaryIterativeSearch">BinaryIterativeSearch</span> ### <span id="BinaryIterativeSearch">BinaryIterativeSearch</span>
<p>二分迭代查找,返回元素索引,未找到元素返回-1参数comparator需要实现包lancetconstraints.Comparator</p>
<p>二分迭代查找,返回元素索引,未找到元素返回-1参数comparator需要实现包lancetconstraints.Comparator。</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func BinaryIterativeSearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) int func BinaryIterativeSearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) int
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -485,44 +512,48 @@ import (
"github.com/duke-git/lancet/v2/algorithm" "github.com/duke-git/lancet/v2/algorithm"
) )
func main() { type intComparator struct{}
type intComparator struct{}
func (c *intComparator) Compare(v1 any, v2 any) int { func (c *intComparator) Compare(v1 any, v2 any) int {
val1, _ := v1.(int) val1, _ := v1.(int)
val2, _ := v2.(int) val2, _ := v2.(int)
//ascending order //ascending order
if val1 < val2 { if val1 < val2 {
return -1 return -1
} else if val1 > val2 { } else if val1 > val2 {
return 1 return 1
}
return 0
} }
return 0
}
var sortedNumbers = []int{1, 2, 3, 4, 5, 6, 7, 8} func main() {
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8}
comparator := &intComparator{} comparator := &intComparator{}
foundIndex := algorithm.BinaryIterativeSearch(sortedNumbers, 5, 0, len(sortedNumbers)-1, comparator)
fmt.Println(foundIndex) //4
notFoundIndex := algorithm.BinaryIterativeSearch(sortedNumbers, 9, 0, len(sortedNumbers)-1, comparator) result1 := algorithm.BinaryIterativeSearch(numbers, 5, 0, len(numbers)-1, comparator)
fmt.Println(notFoundIndex) //-1 result2 := algorithm.BinaryIterativeSearch(numbers, 9, 0, len(numbers)-1, comparator)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 4
// -1
} }
``` ```
### <span id="LinearSearch">LinearSearch</span> ### <span id="LinearSearch">LinearSearch</span>
<p>线性查找,返回元素索引,未找到元素返回-1参数comparator需要实现包lancetconstraints.Comparator</p>
<p>基于传入的相等函数线性查找元素,返回元素索引,未找到元素返回-1。</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func LinearSearch[T any](slice []T, target T, comparator lancetconstraints.Comparator) int func LinearSearch[T any](slice []T, target T, equal func(a, b T) bool) int
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -533,36 +564,27 @@ import (
) )
func main() { func main() {
type intComparator struct{} numbers := []int{3, 4, 5, 3, 2, 1}
func (c *intComparator) Compare(v1 any, v2 any) int { equalFunc := func(a, b int) bool {
val1, _ := v1.(int) return a == b
val2, _ := v2.(int)
//ascending order
if val1 < val2 {
return -1
} else if val1 > val2 {
return 1
}
return 0
} }
intSlice := []int{2, 1, 5, 3, 6, 4} result1 := algorithm.LinearSearch(numbers, 3, equalFunc)
comparator := &intComparator{} result2 := algorithm.LinearSearch(numbers, 6, equalFunc)
foundIndex := algorithm.LinearSearch(intSlice, 5, comparator)
fmt.Println(foundIndex) //2
notFoundIndex := algorithm.LinearSearch(sortedNumbers, 0, comparator) fmt.Println(result1)
fmt.Println(notFoundIndex) //-1 fmt.Println(result2)
// Output:
// 0
// -1
} }
``` ```
### <span id="LRUCache">LRUCache</span> ### <span id="LRUCache">LRUCache</span>
<p>lru实现缓存</p>
<p>lru算法实现缓存。</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -573,7 +595,8 @@ func (l *LRUCache[K, V]) Put(key K, value V)
func (l *LRUCache[K, V]) Delete(key K) bool func (l *LRUCache[K, V]) Delete(key K) bool
func (l *LRUCache[K, V]) Len() int func (l *LRUCache[K, V]) Len() int
``` ```
<b>Example:</b>
<b>示例:</b>
```go ```go
package main package main
@@ -588,14 +611,26 @@ func main() {
cache.Put(1, 1) cache.Put(1, 1)
cache.Put(2, 2) cache.Put(2, 2)
cache.Put(3, 3)
fmt.Println(cache.Len()) // 3 result1, ok1 := cache.Get(1)
result2, ok2 := cache.Get(2)
result3, ok3 := cache.Get(3)
v, ok := cache.Get(1) fmt.Println(result1, ok1)
fmt.Println(v, ok) // 1 true fmt.Println(result2, ok2)
fmt.Println(result3, ok3)
ok = cache.Delete(1) fmt.Println(cache.Len())
fmt.Println(ok) // true
ok := cache.Delete(2)
fmt.Println(ok)
// Output:
// 1 true
// 2 true
// 0 false
// 2
// true
} }
``` ```

View File

@@ -61,8 +61,6 @@ func main() {
} }
``` ```
### <span id="Bridge">Bridge</span> ### <span id="Bridge">Bridge</span>
<p>Link multiple channels into one channel until cancel the context.</p> <p>Link multiple channels into one channel until cancel the context.</p>
@@ -84,39 +82,37 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
genVals := func() <-chan <-chan int { genVals := func() <-chan <-chan int {
out := make(chan (<-chan int)) out := make(chan (<-chan int))
go func() { go func() {
defer close(out) defer close(out)
for i := 1; i <= 5; i++ { for i := 1; i <= 5; i++ {
stream := make(chan int, 1) stream := make(chan int, 1)
stream <- i stream <- i
close(stream) close(stream)
out <- stream out <- stream
} }
}() }()
return out return out
} }
for v := range c.Bridge(ctx, genVals()) { for v := range c.Bridge(ctx, genVals()) {
fmt.Println(v) fmt.Println(v)
} }
// Output:
// 1 // Output:
// 2 // 1
// 3 // 2
// 4 // 3
// 5 // 4
// 5
} }
``` ```
### <span id="FanIn">FanIn</span> ### <span id="FanIn">FanIn</span>
<p>Merge multiple channels into one channel until cancel the context.</p> <p>Merge multiple channels into one channel until cancel the context.</p>
@@ -138,25 +134,24 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
channels := make([]<-chan int, 2) channels := make([]<-chan int, 2)
for i := 0; i < 2; i++ { for i := 0; i < 2; i++ {
channels[i] = c.Take(ctx, c.Repeat(ctx, i), 2) channels[i] = c.Take(ctx, c.Repeat(ctx, i), 2)
} }
chs := c.FanIn(ctx, channels...) chs := c.FanIn(ctx, channels...)
for v := range chs { for v := range chs {
fmt.Println(v) //1 1 0 0 or 0 0 1 1 fmt.Println(v) //1 1 0 0 or 0 0 1 1
} }
} }
``` ```
### <span id="Repeat">Repeat</span> ### <span id="Repeat">Repeat</span>
<p>Create channel, put values into the channel repeatly until cancel the context.</p> <p>Create channel, put values into the channel repeatly until cancel the context.</p>
@@ -178,25 +173,24 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
intStream := c.Take(ctx, c.Repeat(ctx, 1, 2), 4) intStream := c.Take(ctx, c.Repeat(ctx, 1, 2), 4)
for v := range intStream { for v := range intStream {
fmt.Println(v) fmt.Println(v)
} }
// Output:
// 1 // Output:
// 2 // 1
// 1 // 2
// 2 // 1
// 2
} }
``` ```
### <span id="Generate">Generate</span> ### <span id="Generate">Generate</span>
<p>Creates a channel, then put values into the channel.</p> <p>Creates a channel, then put values into the channel.</p>
@@ -218,20 +212,20 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
intStream := c.Generate(ctx, 1, 2, 3) intStream := c.Generate(ctx, 1, 2, 3)
fmt.Println(<-intStream) fmt.Println(<-intStream)
fmt.Println(<-intStream) fmt.Println(<-intStream)
fmt.Println(<-intStream) fmt.Println(<-intStream)
// Output: // Output:
// 1 // 1
// 2 // 2
// 3 // 3
} }
``` ```
@@ -256,28 +250,27 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
fn := func() string { fn := func() string {
return "hello" return "hello"
} }
c := concurrency.NewChannel[string]() c := concurrency.NewChannel[string]()
intStream := c.Take(ctx, c.RepeatFn(ctx, fn), 3) intStream := c.Take(ctx, c.RepeatFn(ctx, fn), 3)
for v := range intStream { for v := range intStream {
fmt.Println(v) fmt.Println(v)
} }
// Output:
// hello // Output:
// hello // hello
// hello // hello
// hello
} }
``` ```
### <span id="Or">Or</span> ### <span id="Or">Or</span>
<p>Read one or more channels into one channel, will close when any readin channel is closed.</p> <p>Read one or more channels into one channel, will close when any readin channel is closed.</p>
@@ -299,31 +292,28 @@ import (
) )
func main() { func main() {
sig := func(after time.Duration) <-chan any { sig := func(after time.Duration) <-chan any {
c := make(chan any) c := make(chan any)
go func() { go func() {
defer close(c) defer close(c)
time.Sleep(after) time.Sleep(after)
}() }()
return c return c
} }
start := time.Now() start := time.Now()
c := concurrency.NewChannel[any]() c := concurrency.NewChannel[any]()
<-c.Or( <-c.Or(
sig(1*time.Second), sig(1*time.Second),
sig(2*time.Second), sig(2*time.Second),
sig(3*time.Second), sig(3*time.Second),
) )
fmt.Println("done after %v", time.Since(start)) //1.003s fmt.Println("done after %v", time.Since(start)) //1.003s
} }
``` ```
### <span id="OrDone">OrDone</span> ### <span id="OrDone">OrDone</span>
<p>Read a channel into another channel, will close until cancel context.</p> <p>Read a channel into another channel, will close until cancel context.</p>
@@ -345,25 +335,23 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
intStream := c.Take(ctx, c.Repeat(ctx, 1), 3) intStream := c.Take(ctx, c.Repeat(ctx, 1), 3)
for v := range c.OrDone(ctx, intStream) { for v := range c.OrDone(ctx, intStream) {
fmt.Println(v) fmt.Println(v)
} }
// Output:
// 1 // Output:
// 1 // 1
// 1 // 1
// 1
} }
``` ```
### <span id="Take">Take</span> ### <span id="Take">Take</span>
<p>Create a channel whose values are taken from another channel with limit number.</p> <p>Create a channel whose values are taken from another channel with limit number.</p>
@@ -385,32 +373,31 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
numbers := make(chan int, 5) numbers := make(chan int, 5)
numbers <- 1 numbers <- 1
numbers <- 2 numbers <- 2
numbers <- 3 numbers <- 3
numbers <- 4 numbers <- 4
numbers <- 5 numbers <- 5
defer close(numbers) defer close(numbers)
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
intStream := c.Take(ctx, numbers, 3) intStream := c.Take(ctx, numbers, 3)
for v := range intStream { for v := range intStream {
fmt.Println(v) fmt.Println(v)
} }
// Output:
// 1 // Output:
// 2 // 1
// 3 // 2
// 3
} }
``` ```
### <span id="Tee">Tee</span> ### <span id="Tee">Tee</span>
<p>Split one chanel into two channels, until cancel the context.</p> <p>Split one chanel into two channels, until cancel the context.</p>
@@ -432,22 +419,23 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
intStream := c.Take(ctx, c.Repeat(ctx, 1), 2) intStream := c.Take(ctx, c.Repeat(ctx, 1), 2)
ch1, ch2 := c.Tee(ctx, intStream) ch1, ch2 := c.Tee(ctx, intStream)
for v := range ch1 { for v := range ch1 {
fmt.Println(v) fmt.Println(v)
fmt.Println(<-ch2) fmt.Println(<-ch2)
} }
// Output:
// 1 // Output:
// 1 // 1
// 1 // 1
// 1 // 1
// 1
} }
``` ```

View File

@@ -61,8 +61,6 @@ func main() {
} }
``` ```
### <span id="Bridge">Bridge</span> ### <span id="Bridge">Bridge</span>
<p>将多个channel链接到一个channel直到取消上下文。</p> <p>将多个channel链接到一个channel直到取消上下文。</p>
@@ -84,39 +82,37 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
genVals := func() <-chan <-chan int { genVals := func() <-chan <-chan int {
out := make(chan (<-chan int)) out := make(chan (<-chan int))
go func() { go func() {
defer close(out) defer close(out)
for i := 1; i <= 5; i++ { for i := 1; i <= 5; i++ {
stream := make(chan int, 1) stream := make(chan int, 1)
stream <- i stream <- i
close(stream) close(stream)
out <- stream out <- stream
} }
}() }()
return out return out
} }
for v := range c.Bridge(ctx, genVals()) { for v := range c.Bridge(ctx, genVals()) {
fmt.Println(v) fmt.Println(v)
} }
// Output:
// 1 // Output:
// 2 // 1
// 3 // 2
// 4 // 3
// 5 // 4
// 5
} }
``` ```
### <span id="FanIn">FanIn</span> ### <span id="FanIn">FanIn</span>
<p>将多个channel合并为一个channel直到取消上下文。</p> <p>将多个channel合并为一个channel直到取消上下文。</p>
@@ -138,25 +134,24 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
channels := make([]<-chan int, 2) channels := make([]<-chan int, 2)
for i := 0; i < 2; i++ { for i := 0; i < 2; i++ {
channels[i] = c.Take(ctx, c.Repeat(ctx, i), 2) channels[i] = c.Take(ctx, c.Repeat(ctx, i), 2)
} }
chs := c.FanIn(ctx, channels...) chs := c.FanIn(ctx, channels...)
for v := range chs { for v := range chs {
fmt.Println(v) //1 1 0 0 or 0 0 1 1 fmt.Println(v) //1 1 0 0 or 0 0 1 1
} }
} }
``` ```
### <span id="Generate">Generate</span> ### <span id="Generate">Generate</span>
<p>根据传入的值生成channel.</p> <p>根据传入的值生成channel.</p>
@@ -178,20 +173,20 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
intStream := c.Generate(ctx, 1, 2, 3) intStream := c.Generate(ctx, 1, 2, 3)
fmt.Println(<-intStream) fmt.Println(<-intStream)
fmt.Println(<-intStream) fmt.Println(<-intStream)
fmt.Println(<-intStream) fmt.Println(<-intStream)
// Output: // Output:
// 1 // 1
// 2 // 2
// 3 // 3
} }
``` ```
@@ -216,26 +211,24 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
intStream := c.Take(ctx, c.Repeat(ctx, 1, 2), 4) intStream := c.Take(ctx, c.Repeat(ctx, 1, 2), 4)
for v := range intStream { for v := range intStream {
fmt.Println(v) fmt.Println(v)
} }
// Output:
// 1 // Output:
// 2 // 1
// 1 // 2
// 2 // 1
// 2
} }
``` ```
### <span id="RepeatFn">RepeatFn</span> ### <span id="RepeatFn">RepeatFn</span>
<p>返回一个channel重复执行函数fn并将结果放入返回的channel直到取消上下文。</p> <p>返回一个channel重复执行函数fn并将结果放入返回的channel直到取消上下文。</p>
@@ -257,28 +250,26 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
fn := func() string { fn := func() string {
return "hello" return "hello"
} }
c := concurrency.NewChannel[string]() c := concurrency.NewChannel[string]()
intStream := c.Take(ctx, c.RepeatFn(ctx, fn), 3) intStream := c.Take(ctx, c.RepeatFn(ctx, fn), 3)
for v := range intStream { for v := range intStream {
fmt.Println(v) fmt.Println(v)
} }
// Output: // Output:
// hello // hello
// hello // hello
// hello // hello
} }
``` ```
### <span id="Or">Or</span> ### <span id="Or">Or</span>
<p>将一个或多个channel读取到一个channel中当任何读取channel关闭时将结束读取。</p> <p>将一个或多个channel读取到一个channel中当任何读取channel关闭时将结束读取。</p>
@@ -300,31 +291,28 @@ import (
) )
func main() { func main() {
sig := func(after time.Duration) <-chan any { sig := func(after time.Duration) <-chan any {
c := make(chan any) c := make(chan any)
go func() { go func() {
defer close(c) defer close(c)
time.Sleep(after) time.Sleep(after)
}() }()
return c return c
} }
start := time.Now() start := time.Now()
c := concurrency.NewChannel[any]() c := concurrency.NewChannel[any]()
<-c.Or( <-c.Or(
sig(1*time.Second), sig(1*time.Second),
sig(2*time.Second), sig(2*time.Second),
sig(3*time.Second), sig(3*time.Second),
) )
fmt.Println("done after %v", time.Since(start)) //1.003s fmt.Println("done after %v", time.Since(start)) //1.003s
} }
``` ```
### <span id="OrDone">OrDone</span> ### <span id="OrDone">OrDone</span>
<p>将一个channel读入另一个channel直到取消上下文。</p> <p>将一个channel读入另一个channel直到取消上下文。</p>
@@ -346,25 +334,23 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
intStream := c.Take(ctx, c.Repeat(ctx, 1), 3) intStream := c.Take(ctx, c.Repeat(ctx, 1), 3)
for v := range c.OrDone(ctx, intStream) { for v := range c.OrDone(ctx, intStream) {
fmt.Println(v) fmt.Println(v)
} }
// Output:
// 1 // Output:
// 1 // 1
// 1 // 1
// 1
} }
``` ```
### <span id="Take">Take</span> ### <span id="Take">Take</span>
<p>返回一个channel其值从另一个channel获取直到取消上下文。</p> <p>返回一个channel其值从另一个channel获取直到取消上下文。</p>
@@ -386,32 +372,31 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
numbers := make(chan int, 5) numbers := make(chan int, 5)
numbers <- 1 numbers <- 1
numbers <- 2 numbers <- 2
numbers <- 3 numbers <- 3
numbers <- 4 numbers <- 4
numbers <- 5 numbers <- 5
defer close(numbers) defer close(numbers)
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
intStream := c.Take(ctx, numbers, 3) intStream := c.Take(ctx, numbers, 3)
for v := range intStream { for v := range intStream {
fmt.Println(v) fmt.Println(v)
} }
// Output:
// 1 // Output:
// 2 // 1
// 3 // 2
// 3
} }
``` ```
### <span id="Tee">Tee</span> ### <span id="Tee">Tee</span>
<p>将一个channel分成两个channel直到取消上下文。</p> <p>将一个channel分成两个channel直到取消上下文。</p>
@@ -433,22 +418,22 @@ import (
) )
func main() { func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
c := concurrency.NewChannel[int]() c := concurrency.NewChannel[int]()
intStream := c.Take(ctx, c.Repeat(ctx, 1), 2) intStream := c.Take(ctx, c.Repeat(ctx, 1), 2)
ch1, ch2 := c.Tee(ctx, intStream) ch1, ch2 := c.Tee(ctx, intStream)
for v := range ch1 { for v := range ch1 {
fmt.Println(v) fmt.Println(v)
fmt.Println(<-ch2) fmt.Println(<-ch2)
} }
// Output: // Output:
// 1 // 1
// 1 // 1
// 1 // 1
// 1 // 1
} }
``` ```

View File

@@ -57,41 +57,52 @@ import (
) )
func main() { func main() {
// bool // bool
fmt.Println(condition.Bool(false)) // false result1 := condition.Bool(false)
fmt.Println(condition.Bool(true)) // true result2 := condition.Bool(true)
fmt.Println(result1) // false
fmt.Println(result2) // true
// integer // integer
fmt.Println(condition.Bool(0)) // false result3 := condition.Bool(0)
fmt.Println(condition.Bool(1)) // true result4 := condition.Bool(1)
fmt.Println(result3) // false
fmt.Println(result4) // true
// float // string
fmt.Println(condition.Bool(0.0)) // false result5 := condition.Bool("")
fmt.Println(condition.Bool(0.1)) // true result6 := condition.Bool(" ")
fmt.Println(result5) // false
fmt.Println(result6) // true
// string // slice
fmt.Println(condition.Bool("")) // false nums := []int{}
fmt.Println(condition.Bool(" ")) // true result7 := condition.Bool(nums)
fmt.Println(condition.Bool("0")) // true
// slice nums = append(nums, 1, 2)
var nums [2]int result8 := condition.Bool(nums)
fmt.Println(condition.Bool(nums)) // false fmt.Println(result7) // false
nums = [2]int{0, 1} fmt.Println(result8) // true
fmt.Println(condition.Bool(nums)) // true
// map // struct
fmt.Println(condition.Bool(map[string]string{})) // false result9 = condition.Bool(struct{}{})
fmt.Println(condition.Bool(map[string]string{"a": "a"})) // true fmt.Println(result8) // false
// struct
fmt.Println(condition.Bool(struct{}{})) // false // Output:
fmt.Println(condition.Bool(time.Now())) // true // false
// true
// false
// true
// false
// true
// false
// true
// false
} }
``` ```
### <span id="And">And</span> ### <span id="And">And</span>
<p>Returns true if both a and b are truthy.</p> <p>Returns true if both a and b are truthy.</p>
@@ -111,10 +122,10 @@ import (
) )
func main() { func main() {
fmt.Println(condition.And(0, 1)) // false fmt.Println(condition.And(0, 1)) // false
fmt.Println(condition.And(0, "")) // false fmt.Println(condition.And(0, "")) // false
fmt.Println(condition.And(0, "0")) // false fmt.Println(condition.And(0, "0")) // false
fmt.Println(condition.And(1, "0")) // true fmt.Println(condition.And(1, "0")) // true
} }
``` ```
@@ -139,10 +150,10 @@ import (
) )
func main() { func main() {
fmt.Println(condition.Or(0, "")) // false fmt.Println(condition.Or(0, "")) // false
fmt.Println(condition.Or(0, 1)) // true fmt.Println(condition.Or(0, 1)) // true
fmt.Println(condition.Or(0, "0")) // true fmt.Println(condition.Or(0, "0")) // true
fmt.Println(condition.Or(1, "0")) // true fmt.Println(condition.Or(1, "0")) // true
} }
``` ```
@@ -167,10 +178,10 @@ import (
) )
func main() { func main() {
fmt.Println(condition.Xor(0, 0)) // false fmt.Println(condition.Xor(0, 0)) // false
fmt.Println(condition.Xor(0, 1)) // true fmt.Println(condition.Xor(0, 1)) // true
fmt.Println(condition.Xor(1, 0)) // true fmt.Println(condition.Xor(1, 0)) // true
fmt.Println(condition.Xor(1, 1)) // false fmt.Println(condition.Xor(1, 1)) // false
} }
``` ```
@@ -195,10 +206,10 @@ import (
) )
func main() { func main() {
fmt.Println(condition.Nor(0, 0)) // true fmt.Println(condition.Nor(0, 0)) // true
fmt.Println(condition.Nor(0, 1)) // false fmt.Println(condition.Nor(0, 1)) // false
fmt.Println(condition.Nor(1, 0)) // false fmt.Println(condition.Nor(1, 0)) // false
fmt.Println(condition.Nor(1, 1)) // false fmt.Println(condition.Nor(1, 1)) // false
} }
``` ```
@@ -222,10 +233,10 @@ import (
) )
func main() { func main() {
fmt.Println(condition.Xnor(0, 0)) // true fmt.Println(condition.Xnor(0, 0)) // true
fmt.Println(condition.Xnor(0, 1)) // false fmt.Println(condition.Xnor(0, 1)) // false
fmt.Println(condition.Xnor(1, 0)) // false fmt.Println(condition.Xnor(1, 0)) // false
fmt.Println(condition.Xnor(1, 1)) // true fmt.Println(condition.Xnor(1, 1)) // true
} }
``` ```
@@ -249,10 +260,10 @@ import (
) )
func main() { func main() {
fmt.Println(condition.Nand(0, 0)) // true fmt.Println(condition.Nand(0, 0)) // true
fmt.Println(condition.Nand(0, 1)) // true fmt.Println(condition.Nand(0, 1)) // true
fmt.Println(condition.Nand(1, 0)) // true fmt.Println(condition.Nand(1, 0)) // true
fmt.Println(condition.Nand(1, 1)) // false fmt.Println(condition.Nand(1, 1)) // false
} }
``` ```
@@ -277,10 +288,18 @@ import (
) )
func main() { func main() {
trueValue := "1" conditionTrue := 2 > 1
falseValue := "0" result1 := condition.TernaryOperator(conditionTrue, 0, 1)
fmt.Println(condition.TernaryOperator(true, trueValue, falseValue)) // "1" conditionFalse := 2 > 3
result2 := condition.TernaryOperator(conditionFalse, 0, 1)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 0
// 1
} }
``` ```

View File

@@ -56,41 +56,51 @@ import (
) )
func main() { func main() {
// bool // bool
fmt.Println(condition.Bool(false)) // false result1 := condition.Bool(false)
fmt.Println(condition.Bool(true)) // true result2 := condition.Bool(true)
fmt.Println(result1) // false
fmt.Println(result2) // true
// integer // integer
fmt.Println(condition.Bool(0)) // false result3 := condition.Bool(0)
fmt.Println(condition.Bool(1)) // true result4 := condition.Bool(1)
fmt.Println(result3) // false
fmt.Println(result4) // true
// float // string
fmt.Println(condition.Bool(0.0)) // false result5 := condition.Bool("")
fmt.Println(condition.Bool(0.1)) // true result6 := condition.Bool(" ")
fmt.Println(result5) // false
fmt.Println(result6) // true
// string // slice
fmt.Println(condition.Bool("")) // false nums := []int{}
fmt.Println(condition.Bool(" ")) // true result7 := condition.Bool(nums)
fmt.Println(condition.Bool("0")) // true
// slice nums = append(nums, 1, 2)
var nums [2]int result8 := condition.Bool(nums)
fmt.Println(condition.Bool(nums)) // false fmt.Println(result7) // false
nums = [2]int{0, 1} fmt.Println(result8) // true
fmt.Println(condition.Bool(nums)) // true
// map // struct
fmt.Println(condition.Bool(map[string]string{})) // false result9 = condition.Bool(struct{}{})
fmt.Println(condition.Bool(map[string]string{"a": "a"})) // true fmt.Println(result8) // false
// struct
fmt.Println(condition.Bool(struct{}{})) // false // Output:
fmt.Println(condition.Bool(time.Now())) // true // false
// true
// false
// true
// false
// true
// false
// true
// false
} }
``` ```
### <span id="And">And</span> ### <span id="And">And</span>
<p>逻辑且操作当切仅当a和b都为true时返回true</p> <p>逻辑且操作当切仅当a和b都为true时返回true</p>
@@ -110,15 +120,13 @@ import (
) )
func main() { func main() {
fmt.Println(condition.And(0, 1)) // false fmt.Println(condition.And(0, 1)) // false
fmt.Println(condition.And(0, "")) // false fmt.Println(condition.And(0, "")) // false
fmt.Println(condition.And(0, "0")) // false fmt.Println(condition.And(0, "0")) // false
fmt.Println(condition.And(1, "0")) // true fmt.Println(condition.And(1, "0")) // true
} }
``` ```
### <span id="Or">Or</span> ### <span id="Or">Or</span>
<p>逻辑或操作当切仅当a和b都为false时返回false</p> <p>逻辑或操作当切仅当a和b都为false时返回false</p>
@@ -138,15 +146,13 @@ import (
) )
func main() { func main() {
fmt.Println(condition.Or(0, "")) // false fmt.Println(condition.Or(0, "")) // false
fmt.Println(condition.Or(0, 1)) // true fmt.Println(condition.Or(0, 1)) // true
fmt.Println(condition.Or(0, "0")) // true fmt.Println(condition.Or(0, "0")) // true
fmt.Println(condition.Or(1, "0")) // true fmt.Println(condition.Or(1, "0")) // true
} }
``` ```
### <span id="Xor">Xor</span> ### <span id="Xor">Xor</span>
<p>逻辑异或操作a和b相同返回falsea和b不相同返回true</p> <p>逻辑异或操作a和b相同返回falsea和b不相同返回true</p>
@@ -166,15 +172,13 @@ import (
) )
func main() { func main() {
fmt.Println(condition.Xor(0, 0)) // false fmt.Println(condition.Xor(0, 0)) // false
fmt.Println(condition.Xor(0, 1)) // true fmt.Println(condition.Xor(0, 1)) // true
fmt.Println(condition.Xor(1, 0)) // true fmt.Println(condition.Xor(1, 0)) // true
fmt.Println(condition.Xor(1, 1)) // false fmt.Println(condition.Xor(1, 1)) // false
} }
``` ```
### <span id="Nor">Nor</span> ### <span id="Nor">Nor</span>
<p>异或的取反操作</p> <p>异或的取反操作</p>
@@ -194,15 +198,13 @@ import (
) )
func main() { func main() {
fmt.Println(condition.Nor(0, 0)) // true fmt.Println(condition.Nor(0, 0)) // true
fmt.Println(condition.Nor(0, 1)) // false fmt.Println(condition.Nor(0, 1)) // false
fmt.Println(condition.Nor(1, 0)) // false fmt.Println(condition.Nor(1, 0)) // false
fmt.Println(condition.Nor(1, 1)) // false fmt.Println(condition.Nor(1, 1)) // false
} }
``` ```
### <span id="Xnor">Xnor</span> ### <span id="Xnor">Xnor</span>
<p>如果a和b都是真的或a和b均是假的则返回true。</p> <p>如果a和b都是真的或a和b均是假的则返回true。</p>
@@ -222,10 +224,10 @@ import (
) )
func main() { func main() {
fmt.Println(condition.Xnor(0, 0)) // true fmt.Println(condition.Xnor(0, 0)) // true
fmt.Println(condition.Xnor(0, 1)) // false fmt.Println(condition.Xnor(0, 1)) // false
fmt.Println(condition.Xnor(1, 0)) // false fmt.Println(condition.Xnor(1, 0)) // false
fmt.Println(condition.Xnor(1, 1)) // true fmt.Println(condition.Xnor(1, 1)) // true
} }
``` ```
@@ -248,15 +250,13 @@ import (
) )
func main() { func main() {
fmt.Println(condition.Nand(0, 0)) // true fmt.Println(condition.Nand(0, 0)) // true
fmt.Println(condition.Nand(0, 1)) // true fmt.Println(condition.Nand(0, 1)) // true
fmt.Println(condition.Nand(1, 0)) // true fmt.Println(condition.Nand(1, 0)) // true
fmt.Println(condition.Nand(1, 1)) // false fmt.Println(condition.Nand(1, 1)) // false
} }
``` ```
### <span id="TernaryOperator">TernaryOperator</span> ### <span id="TernaryOperator">TernaryOperator</span>
<p>三元运算符</p> <p>三元运算符</p>
@@ -276,10 +276,18 @@ import (
) )
func main() { func main() {
trueValue := "1" conditionTrue := 2 > 1
falseValue := "0" result1 := condition.TernaryOperator(conditionTrue, 0, 1)
fmt.Println(condition.TernaryOperator(true, trueValue, falseValue)) // "1" conditionFalse := 2 > 3
result2 := condition.TernaryOperator(conditionFalse, 0, 1)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 0
// 1
} }
``` ```

View File

@@ -40,8 +40,6 @@ import (
## Documentation ## Documentation
### <span id="ColorHexToRGB">ColorHexToRGB</span> ### <span id="ColorHexToRGB">ColorHexToRGB</span>
<p>Convert color hex to color rgb.</p> <p>Convert color hex to color rgb.</p>
@@ -63,12 +61,14 @@ import (
func main() { func main() {
colorHex := "#003366" colorHex := "#003366"
r, g, b := convertor.ColorHexToRGB(colorHex) r, g, b := convertor.ColorHexToRGB(colorHex)
fmt.Println(r, g, b) //0,51,102
fmt.Println(r, g, b)
// Output:
// 0 51 102
} }
``` ```
### <span id="ColorRGBToHex">ColorRGBToHex</span> ### <span id="ColorRGBToHex">ColorRGBToHex</span>
<p>Convert color rgb to color hex.</p> <p>Convert color rgb to color hex.</p>
@@ -92,14 +92,15 @@ func main() {
r := 0 r := 0
g := 51 g := 51
b := 102 b := 102
colorHex := convertor.ColorRGBToHex(r, g, b) colorHex := ColorRGBToHex(r, g, b)
fmt.Println(colorHex) //#003366 fmt.Println(colorHex)
// Output:
// #003366
} }
``` ```
### <span id="ToBool">ToBool</span> ### <span id="ToBool">ToBool</span>
<p>Convert string to bool. Use strconv.ParseBool.</p> <p>Convert string to bool. Use strconv.ParseBool.</p>
@@ -120,22 +121,26 @@ import (
) )
func main() { func main() {
v1, _ := convertor.ToBool("1") cases := []string{"1", "true", "True", "false", "False", "0", "123", "0.0", "abc"}
fmt.Println(v1) //true
v2, _ := convertor.ToBool("true") for i := 0; i < len(cases); i++ {
fmt.Println(v2) //true result, _ := convertor.ToBool(cases[i])
fmt.Println(result)
}
v3, _ := convertor.ToBool("True") // Output:
fmt.Println(v3) //true // true
// true
v4, _ := convertor.ToBool("123") // true
fmt.Println(v4) //false // false
// false
// false
// false
// false
// false
} }
``` ```
### <span id="ToBytes">ToBytes</span> ### <span id="ToBytes">ToBytes</span>
<p>Convert value to byte slice.</p> <p>Convert value to byte slice.</p>
@@ -156,16 +161,18 @@ import (
) )
func main() { func main() {
bytesData, err := convertor.ToBytes("0") bytesData, err := convertor.ToBytes("abc")
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
} }
fmt.Println(bytesData) //[]bytes{3, 4, 0, 0}
fmt.Println(bytesData)
// Output:
// [97 98 99]
} }
``` ```
### <span id="ToChar">ToChar</span> ### <span id="ToChar">ToChar</span>
<p>Convert string to char slice.</p> <p>Convert string to char slice.</p>
@@ -186,18 +193,21 @@ import (
) )
func main() { func main() {
chars := convertor.ToChar("") result1 := convertor.ToChar("")
fmt.Println(chars) //[]string{""} result2 := convertor.ToChar("abc")
result3 := convertor.ToChar("1 2#3")
chars = convertor.ToChar("abc") fmt.Println(result1)
fmt.Println(chars) //[]string{"a", "b", "c"} fmt.Println(result2)
fmt.Println(result3)
chars = convertor.ToChar("1 2#3") // Output:
fmt.Println(chars) //[]string{"1", " ", "2", "#", "3"} // []
// [a b c]
// [1 2 # 3]
} }
``` ```
### <span id="ToChannel">ToChannel</span> ### <span id="ToChannel">ToChannel</span>
<p>Convert a collection of elements to a read-only channel.</p> <p>Convert a collection of elements to a read-only channel.</p>
@@ -219,23 +229,21 @@ import (
func main() { func main() {
ch := convertor.ToChannel([]int{1, 2, 3}) ch := convertor.ToChannel([]int{1, 2, 3})
result1 := <-ch
result2 := <-ch
result3 := <-ch
val1, _ := <-ch fmt.Println(result1)
fmt.Println(val1) //1 fmt.Println(result2)
fmt.Println(result3)
val2, _ := <-ch // Output:
fmt.Println(val2) //2 // 1
// 2
val3, _ := <-ch // 3
fmt.Println(val3) //3
_, ok := <-ch
fmt.Println(ok) //false
} }
``` ```
### <span id="ToFloat">ToFloat</span> ### <span id="ToFloat">ToFloat</span>
<p>Convert value to a float64 value. If param is a invalid floatable, will return 0.0 and error. </p> <p>Convert value to a float64 value. If param is a invalid floatable, will return 0.0 and error. </p>
@@ -256,19 +264,30 @@ import (
) )
func main() { func main() {
v, err := convertor.ToFloat("") result1, _ := convertor.ToFloat("")
if err != nil { result2, err := convertor.ToFloat("abc")
fmt.Println(err) //strconv.ParseFloat: parsing "": invalid syntax result3, _ := convertor.ToFloat("-1")
} result4, _ := convertor.ToFloat("-.11")
fmt.Println(v) //0 result5, _ := convertor.ToFloat("1.23e3")
result6, _ := convertor.ToFloat(true)
v, _ = convertor.ToFloat("-.11") fmt.Println(result1)
fmt.Println(v) //-0.11 fmt.Println(result2, err)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
// Output:
// 0
// 0 strconv.ParseFloat: parsing "": invalid syntax
// -1
// -0.11
// 1230
// 0
} }
``` ```
### <span id="ToInt">ToInt</span> ### <span id="ToInt">ToInt</span>
<p>Convert value to a int64 value. If param is a invalid intable, will return 0 and error. </p> <p>Convert value to a int64 value. If param is a invalid intable, will return 0 and error. </p>
@@ -289,19 +308,27 @@ import (
) )
func main() { func main() {
v, err := convertor.ToInt("") result1, _ := convertor.ToInt("123")
if err != nil { result2, _ := convertor.ToInt("-123")
fmt.Println(err) //strconv.ParseInt: parsing "": invalid syntax result3, _ := convertor.ToInt(float64(12.3))
} result4, err := convertor.ToInt("abc")
fmt.Println(v) //0 result5, _ := convertor.ToInt(true)
v, _ = convertor.ToFloat(1.12) fmt.Println(result1)
fmt.Println(v) //1 fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4, err)
fmt.Println(result5)
// Output:
// 123
// -123
// 12
// 0 strconv.ParseInt: parsing "": invalid syntax
// 0
} }
``` ```
### <span id="ToJson">ToJson</span> ### <span id="ToJson">ToJson</span>
<p>Convert interface to json string. If param can't be converted, will return "" and error. </p> <p>Convert interface to json string. If param can't be converted, will return "" and error. </p>
@@ -322,14 +349,20 @@ import (
) )
func main() { func main() {
var aMap = map[string]int{"a": 1, "b": 2, "c": 3} aMap := map[string]int{"a": 1, "b": 2, "c": 3}
jsonStr, _ := convertor.ToJson(aMap) result, err := ToJson(aMap)
fmt.Printf("%q", jsonStr) //"{\"a\":1,\"b\":2,\"c\":3}"
if err != nil {
fmt.Printf("%v", err)
}
fmt.Println(result)
// Output:
// {"a":1,"b":2,"c":3}
} }
``` ```
### <span id="ToMap">ToMap</span> ### <span id="ToMap">ToMap</span>
<p>Convert a slice of structs to a map based on iteratee function. </p> <p>Convert a slice of structs to a map based on iteratee function. </p>
@@ -358,16 +391,18 @@ func main() {
{name: "Hello", code: 100}, {name: "Hello", code: 100},
{name: "Hi", code: 101}, {name: "Hi", code: 101},
} }
result := convertor.ToMap(messages, func(msg Message) (int, string) { result := convertor.ToMap(messages, func(msg Message) (int, string) {
return msg.code, msg.name return msg.code, msg.name
}) })
fmt.Println(result) //{100: "Hello", 101: "Hi"} fmt.Println(result)
// Output:
// map[100:Hello 101:Hi]
} }
``` ```
### <span id="ToPointer">ToPointer</span> ### <span id="ToPointer">ToPointer</span>
<p>Returns a pointer to passed value. </p> <p>Returns a pointer to passed value. </p>
@@ -389,11 +424,13 @@ import (
func main() { func main() {
result := convertor.ToPointer(123) result := convertor.ToPointer(123)
fmt.Println(*result) //123 fmt.Println(*result)
// Output:
// 123
} }
``` ```
### <span id="ToString">ToString</span> ### <span id="ToString">ToString</span>
<p>ToString convert value to string, for number, string, []byte, will convert to string. For other type (slice, map, array, struct) will call json.Marshal</p> <p>ToString convert value to string, for number, string, []byte, will convert to string. For other type (slice, map, array, struct) will call json.Marshal</p>
@@ -414,13 +451,33 @@ import (
) )
func main() { func main() {
fmt.Printf("%q", convertor.ToString(1)) //"1" result1 := convertor.ToString("")
fmt.Printf("%q", convertor.ToString(1.1)) //"1.1" result2 := convertor.ToString(nil)
fmt.Printf("%q", convertor.ToString([]int{1, 2, 3})) //"[1,2,3]" result3 := convertor.ToString(0)
result4 := convertor.ToString(1.23)
result5 := convertor.ToString(true)
result6 := convertor.ToString(false)
result7 := convertor.ToString([]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:
//
//
// 0
// 1.23
// true
// false
// [1,2,3]
} }
``` ```
### <span id="StructToMap">StructToMap</span> ### <span id="StructToMap">StructToMap</span>
<p>Convert struct to map, only convert exported field, struct field tag `json` should be set.</p> <p>Convert struct to map, only convert exported field, struct field tag `json` should be set.</p>
@@ -451,12 +508,13 @@ func main() {
} }
pm, _ := convertor.StructToMap(p) pm, _ := convertor.StructToMap(p)
fmt.Printf("type: %T, value: %s", pm, pm) //type: map[string]interface {}, value: map[name:test] fmt.Println(pm)
// Output:
// map[name:test]
} }
``` ```
### <span id="MapToSlice">MapToSlice</span> ### <span id="MapToSlice">MapToSlice</span>
<p>Convert a map to a slice based on iteratee function.</p> <p>Convert a map to a slice based on iteratee function.</p>
@@ -508,12 +566,13 @@ import (
func main() { func main() {
byteData, _ := convertor.EncodeByte("abc") byteData, _ := convertor.EncodeByte("abc")
fmt.Println(byteData) //[]byte{6, 12, 0, 3, 97, 98, 99} fmt.Println(byteData)
// Output:
// [6 12 0 3 97 98 99]
} }
``` ```
### <span id="DecodeByte">DecodeByte</span> ### <span id="DecodeByte">DecodeByte</span>
<p>Decode byte data to target object. target should be a pointer instance.</p> <p>Decode byte data to target object. target should be a pointer instance.</p>
@@ -535,8 +594,16 @@ import (
func main() { func main() {
var result string var result string
byteData := []byte{6, 12, 0, 3, 97, 98, 99} byteData := []byte{6, 12, 0, 3, 97, 98, 99}
convertor.DecodeByte(byteData, &result)
fmt.Println(result) //"abc" err := convertor.DecodeByte(byteData, &result)
if err != nil {
return
}
fmt.Println(result)
// Output:
// abc
} }
``` ```

View File

@@ -43,16 +43,15 @@ import (
## 文档 ## 文档
### <span id="ColorHexToRGB">ColorHexToRGB</span> ### <span id="ColorHexToRGB">ColorHexToRGB</span>
<p>颜色值十六进制转rgb</p> <p>颜色值十六进制转rgb</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ColorHexToRGB(colorHex string) (red, green, blue int) func ColorHexToRGB(colorHex string) (red, green, blue int)
``` ```
<b>列子:</b> <b>示例:</b>
```go ```go
package main package main
@@ -65,22 +64,24 @@ import (
func main() { func main() {
colorHex := "#003366" colorHex := "#003366"
r, g, b := convertor.ColorHexToRGB(colorHex) r, g, b := convertor.ColorHexToRGB(colorHex)
fmt.Println(r, g, b) //0,51,102
fmt.Println(r, g, b)
// Output:
// 0 51 102
} }
``` ```
### <span id="ColorRGBToHex">ColorRGBToHex</span> ### <span id="ColorRGBToHex">ColorRGBToHex</span>
<p>颜色值rgb转十六进制</p> <p>颜色值rgb转十六进制</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ColorRGBToHex(red, green, blue int) string func ColorRGBToHex(red, green, blue int) string
``` ```
<b>列子:</b> <b>示例:</b>
```go ```go
package main package main
@@ -94,24 +95,25 @@ func main() {
r := 0 r := 0
g := 51 g := 51
b := 102 b := 102
colorHex := convertor.ColorRGBToHex(r, g, b) colorHex := ColorRGBToHex(r, g, b)
fmt.Println(colorHex) //#003366 fmt.Println(colorHex)
// Output:
// #003366
} }
``` ```
### <span id="ToBool">ToBool</span> ### <span id="ToBool">ToBool</span>
<p>字符串转布尔类型使用strconv.ParseBool</p> <p>字符串转布尔类型使用strconv.ParseBool</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ToBool(s string) (bool, error) func ToBool(s string) (bool, error)
``` ```
<b>列子:</b> <b>示例:</b>
```go ```go
package main package main
@@ -122,32 +124,36 @@ import (
) )
func main() { func main() {
v1, _ := convertor.ToBool("1") cases := []string{"1", "true", "True", "false", "False", "0", "123", "0.0", "abc"}
fmt.Println(v1) //true
v2, _ := convertor.ToBool("true") for i := 0; i < len(cases); i++ {
fmt.Println(v2) //true result, _ := convertor.ToBool(cases[i])
fmt.Println(result)
}
v3, _ := convertor.ToBool("True") // Output:
fmt.Println(v3) //true // true
// true
v4, _ := convertor.ToBool("123") // true
fmt.Println(v4) //false // false
// false
// false
// false
// false
// false
} }
``` ```
### <span id="ToBytes">ToBytes</span> ### <span id="ToBytes">ToBytes</span>
<p>interface转字节切片.</p> <p>Interface转字节切片</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ToBytes(data any) ([]byte, error) func ToBytes(data any) ([]byte, error)
``` ```
<b>列子:</b> <b>示例:</b>
```go ```go
package main package main
@@ -158,26 +164,28 @@ import (
) )
func main() { func main() {
bytesData, err := convertor.ToBytes("0") bytesData, err := convertor.ToBytes("abc")
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
} }
fmt.Println(bytesData) //[]bytes{3, 4, 0, 0}
fmt.Println(bytesData)
// Output:
// [97 98 99]
} }
``` ```
### <span id="ToChar">ToChar</span> ### <span id="ToChar">ToChar</span>
<p>字符串转字符切片</p> <p>字符串转字符切片</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ToChar(s string) []string func ToChar(s string) []string
``` ```
<b>列子:</b> <b>示例:</b>
```go ```go
package main package main
@@ -188,29 +196,31 @@ import (
) )
func main() { func main() {
chars := convertor.ToChar("") result1 := convertor.ToChar("")
fmt.Println(chars) //[]string{""} result2 := convertor.ToChar("abc")
result3 := convertor.ToChar("1 2#3")
chars = convertor.ToChar("abc") fmt.Println(result1)
fmt.Println(chars) //[]string{"a", "b", "c"} fmt.Println(result2)
fmt.Println(result3)
chars = convertor.ToChar("1 2#3") // Output:
fmt.Println(chars) //[]string{"1", " ", "2", "#", "3"} // []
// [a b c]
// [1 2 # 3]
} }
``` ```
### <span id="ToChannel">ToChannel</span> ### <span id="ToChannel">ToChannel</span>
<p>将切片转为只读channel</p> <p>将切片转为只读channel</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ToChannel[T any](array []T) <-chan T func ToChannel[T any](array []T) <-chan T
``` ```
<b>例:</b> <b>例:</b>
```go ```go
package main package main
@@ -222,33 +232,31 @@ import (
func main() { func main() {
ch := convertor.ToChannel([]int{1, 2, 3}) ch := convertor.ToChannel([]int{1, 2, 3})
result1 := <-ch
result2 := <-ch
result3 := <-ch
val1, _ := <-ch fmt.Println(result1)
fmt.Println(val1) //1 fmt.Println(result2)
fmt.Println(result3)
val2, _ := <-ch // Output:
fmt.Println(val2) //2 // 1
// 2
val3, _ := <-ch // 3
fmt.Println(val3) //3
_, ok := <-ch
fmt.Println(ok) //false
} }
``` ```
### <span id="ToFloat">ToFloat</span> ### <span id="ToFloat">ToFloat</span>
<p>将interface转成float64类型如果参数无法转换会返回0和error</p> <p>将interface转成float64类型如果参数无法转换会返回0和error</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ToFloat(value any) (float64, error) func ToFloat(value any) (float64, error)
``` ```
<b>列子:</b> <b>示例:</b>
```go ```go
package main package main
@@ -259,29 +267,40 @@ import (
) )
func main() { func main() {
v, err := convertor.ToFloat("") result1, _ := convertor.ToFloat("")
if err != nil { result2, err := convertor.ToFloat("abc")
fmt.Println(err) //strconv.ParseFloat: parsing "": invalid syntax result3, _ := convertor.ToFloat("-1")
} result4, _ := convertor.ToFloat("-.11")
fmt.Println(v) //0 result5, _ := convertor.ToFloat("1.23e3")
result6, _ := convertor.ToFloat(true)
v, _ = convertor.ToFloat("-.11") fmt.Println(result1)
fmt.Println(v) //-0.11 fmt.Println(result2, err)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
// Output:
// 0
// 0 strconv.ParseFloat: parsing "": invalid syntax
// -1
// -0.11
// 1230
// 0
} }
``` ```
### <span id="ToInt">ToInt</span> ### <span id="ToInt">ToInt</span>
<p>将interface转成int64类型如果参数无法转换会返回0和error</p> <p>将interface转成int64类型如果参数无法转换会返回0和error</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ToInt(value any) (int64, error) func ToInt(value any) (int64, error)
``` ```
<b>例:</b> <b>例:</b>
```go ```go
package main package main
@@ -292,29 +311,37 @@ import (
) )
func main() { func main() {
v, err := convertor.ToInt("") result1, _ := convertor.ToInt("123")
if err != nil { result2, _ := convertor.ToInt("-123")
fmt.Println(err) //strconv.ParseInt: parsing "": invalid syntax result3, _ := convertor.ToInt(float64(12.3))
} result4, err := convertor.ToInt("abc")
fmt.Println(v) //0 result5, _ := convertor.ToInt(true)
v, _ = convertor.ToFloat(1.12) fmt.Println(result1)
fmt.Println(v) //1 fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4, err)
fmt.Println(result5)
// Output:
// 123
// -123
// 12
// 0 strconv.ParseInt: parsing "": invalid syntax
// 0
} }
``` ```
### <span id="ToJson">ToJson</span> ### <span id="ToJson">ToJson</span>
<p>将interface转成json字符串如果参数无法转换会返回""和error</p> <p>将interface转成json字符串如果参数无法转换会返回""和error</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ToJson(value any) (string, error) func ToJson(value any) (string, error)
``` ```
<b>列子:</b> <b>示例:</b>
```go ```go
package main package main
@@ -325,24 +352,30 @@ import (
) )
func main() { func main() {
var aMap = map[string]int{"a": 1, "b": 2, "c": 3} aMap := map[string]int{"a": 1, "b": 2, "c": 3}
jsonStr, _ := convertor.ToJson(aMap) result, err := ToJson(aMap)
fmt.Printf("%q", jsonStr) //"{\"a\":1,\"b\":2,\"c\":3}"
if err != nil {
fmt.Printf("%v", err)
}
fmt.Println(result)
// Output:
// {"a":1,"b":2,"c":3}
} }
``` ```
### <span id="ToMap">ToMap</span> ### <span id="ToMap">ToMap</span>
<p>将切片转为map</p> <p>将切片转为map</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ToMap[T any, K comparable, V any](array []T, iteratee func(T) (K, V)) map[K]V func ToMap[T any, K comparable, V any](array []T, iteratee func(T) (K, V)) map[K]V
``` ```
<b>例:</b> <b>例:</b>
```go ```go
package main package main
@@ -361,26 +394,28 @@ func main() {
{name: "Hello", code: 100}, {name: "Hello", code: 100},
{name: "Hi", code: 101}, {name: "Hi", code: 101},
} }
result := convertor.ToMap(messages, func(msg Message) (int, string) { result := convertor.ToMap(messages, func(msg Message) (int, string) {
return msg.code, msg.name return msg.code, msg.name
}) })
fmt.Println(result) //{100: "Hello", 101: "Hi"} fmt.Println(result)
// Output:
// map[100:Hello 101:Hi]
} }
``` ```
### <span id="ToPointer">ToPointer</span> ### <span id="ToPointer">ToPointer</span>
<p>返回传入值的指针</p> <p>返回传入值的指针</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ToPointer[T any](value T) *T func ToPointer[T any](value T) *T
``` ```
<b>例:</b> <b>例:</b>
```go ```go
package main package main
@@ -392,22 +427,23 @@ import (
func main() { func main() {
result := convertor.ToPointer(123) result := convertor.ToPointer(123)
fmt.Println(*result) //123 fmt.Println(*result)
// Output:
// 123
} }
``` ```
### <span id="ToString">ToString</span> ### <span id="ToString">ToString</span>
<p>将值转换为字符串,对于数字、字符串、[]byte将转换为字符串。 对于其他类型(切片、映射、数组、结构)将调用 json.Marshal</p> <p>将值转换为字符串,对于数字、字符串、[]byte将转换为字符串。 对于其他类型(切片、映射、数组、结构)将调用 json.Marshal</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func ToString(value any) string func ToString(value any) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
package main package main
@@ -418,24 +454,43 @@ import (
) )
func main() { func main() {
fmt.Printf("%q", convertor.ToString(1)) //"1" result1 := convertor.ToString("")
fmt.Printf("%q", convertor.ToString(1.1)) //"1.1" result2 := convertor.ToString(nil)
fmt.Printf("%q", convertor.ToString([]int{1, 2, 3})) //"[1,2,3]" result3 := convertor.ToString(0)
result4 := convertor.ToString(1.23)
result5 := convertor.ToString(true)
result6 := convertor.ToString(false)
result7 := convertor.ToString([]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:
//
//
// 0
// 1.23
// true
// false
// [1,2,3]
} }
``` ```
### <span id="StructToMap">StructToMap</span> ### <span id="StructToMap">StructToMap</span>
<p>将struct转成map只会转换struct中可导出的字段。struct中导出字段需要设置json tag标记</p> <p>将struct转成map只会转换struct中可导出的字段。struct中导出字段需要设置json tag标记</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func StructToMap(value any) (map[string]any, error) func StructToMap(value any) (map[string]any, error)
``` ```
<b>列子:</b> <b>示例:</b>
```go ```go
package main package main
@@ -456,22 +511,23 @@ func main() {
} }
pm, _ := convertor.StructToMap(p) pm, _ := convertor.StructToMap(p)
fmt.Printf("type: %T, value: %s", pm, pm) //type: map[string]interface {}, value: map[name:test] fmt.Println(pm)
// Output:
// map[name:test]
} }
``` ```
### <span id="MapToSlice">MapToSlice</span> ### <span id="MapToSlice">MapToSlice</span>
<p>map中key和value执行函数iteratee后转为切片</p> <p>map中key和value执行函数iteratee后转为切片</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func MapToSlice[T any, K comparable, V any](aMap map[K]V, iteratee func(K, V) T) []T func MapToSlice[T any, K comparable, V any](aMap map[K]V, iteratee func(K, V) T) []T
``` ```
<b>例:</b> <b>例:</b>
```go ```go
package main package main
@@ -491,18 +547,16 @@ func main() {
} }
``` ```
### <span id="EncodeByte">EncodeByte</span> ### <span id="EncodeByte">EncodeByte</span>
<p>将data编码成字节切片</p> <p>将data编码成字节切片</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func EncodeByte(data any) ([]byte, error) func EncodeByte(data any) ([]byte, error)
``` ```
<b>例:</b> <b>例:</b>
```go ```go
package main package main
@@ -514,22 +568,23 @@ import (
func main() { func main() {
byteData, _ := convertor.EncodeByte("abc") byteData, _ := convertor.EncodeByte("abc")
fmt.Println(byteData) //[]byte{6, 12, 0, 3, 97, 98, 99} fmt.Println(byteData)
// Output:
// [6 12 0 3 97 98 99]
} }
``` ```
### <span id="DecodeByte">DecodeByte</span> ### <span id="DecodeByte">DecodeByte</span>
<p>解码字节切片到目标对象,目标对象需要传入一个指针实例</p> <p>解码字节切片到目标对象,目标对象需要传入一个指针实例</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func DecodeByte(data []byte, target any) error func DecodeByte(data []byte, target any) error
``` ```
<b>例:</b> <b>例:</b>
```go ```go
package main package main
@@ -541,8 +596,16 @@ import (
func main() { func main() {
var result string var result string
byteData := []byte{6, 12, 0, 3, 97, 98, 99} byteData := []byte{6, 12, 0, 3, 97, 98, 99}
convertor.DecodeByte(byteData, &result)
fmt.Println(result) //"abc" err := convertor.DecodeByte(byteData, &result)
if err != nil {
return
}
fmt.Println(result)
// Output:
// abc
} }
``` ```

View File

@@ -61,8 +61,6 @@ import (
## Documentation ## Documentation
### <span id="AesEcbEncrypt">AesEcbEncrypt</span> ### <span id="AesEcbEncrypt">AesEcbEncrypt</span>
<p>Encrypt data with key use AES ECB algorithm. Length of `key` param should be 16, 24 or 32.</p> <p>Encrypt data with key use AES ECB algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -83,16 +81,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefghijklmnop" key := "abcdefghijklmnop"
encrypted := cryptor.AesEcbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted)) encrypted := cryptor.AesEcbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesEcbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="AesEcbDecrypt">AesEcbDecrypt</span> ### <span id="AesEcbDecrypt">AesEcbDecrypt</span>
<p>Decrypt data with key use AES ECB algorithm. Length of `key` param should be 16, 24 or 32.</p> <p>Decrypt data with key use AES ECB algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -113,16 +114,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefghijklmnop" key := "abcdefghijklmnop"
encrypted := cryptor.AesEcbEncrypt([]byte(data), []byte(key)) encrypted := cryptor.AesEcbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesEcbDecrypt(encrypted, []byte(key)) decrypted := cryptor.AesEcbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="AesCbcEncrypt">AesCbcEncrypt</span> ### <span id="AesCbcEncrypt">AesCbcEncrypt</span>
<p>Encrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32.</p> <p>Encrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -143,16 +147,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefghijklmnop" key := "abcdefghijklmnop"
encrypted := cryptor.AesCbcEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted)) encrypted := cryptor.AesCbcEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesCbcDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="AesCbcDecrypt">AesCbcDecrypt</span> ### <span id="AesCbcDecrypt">AesCbcDecrypt</span>
<p>Decrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32.</p> <p>Decrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -174,16 +181,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefghijklmnop" key := "abcdefghijklmnop"
encrypted := cryptor.AesCbcEncrypt([]byte(data), []byte(key)) encrypted := cryptor.AesCbcEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesCbcDecrypt(encrypted, []byte(key)) decrypted := cryptor.AesCbcDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="AesCtrCrypt">AesCtrCrypt</span> ### <span id="AesCtrCrypt">AesCtrCrypt</span>
<p>Encrypt or decrypt data with key use AES CTR algorithm. Length of `key` param should be 16, 24 or 32.</p> <p>Encrypt or decrypt data with key use AES CTR algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -205,17 +215,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefghijklmnop" key := "abcdefghijklmnop"
encrypted := cryptor.AesCtrCrypt([]byte(data), []byte(key)) encrypted := cryptor.AesCtrCrypt([]byte(data), []byte(key))
decrypted := cryptor.AesCtrCrypt(encrypted, []byte(key)) decrypted := cryptor.AesCtrCrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="AesCfbEncrypt">AesCfbEncrypt</span> ### <span id="AesCfbEncrypt">AesCfbEncrypt</span>
<p>Encrypt data with key use AES CFB algorithm. Length of `key` param should be 16, 24 or 32.</p> <p>Encrypt data with key use AES CFB algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -237,15 +249,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefghijklmnop" key := "abcdefghijklmnop"
encrypted := cryptor.AesCfbEncrypt([]byte(data), []byte(key)) encrypted := cryptor.AesCfbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted)) decrypted := cryptor.AesCfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="AesCfbDecrypt">AesCfbDecrypt</span> ### <span id="AesCfbDecrypt">AesCfbDecrypt</span>
<p>Decrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32.</p> <p>Decrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -267,16 +283,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefghijklmnop" key := "abcdefghijklmnop"
encrypted := cryptor.AesCfbEncrypt([]byte(data), []byte(key)) encrypted := cryptor.AesCfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesCfbDecrypt(encrypted, []byte(key)) decrypted := cryptor.AesCfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="AesOfbEncrypt">AesOfbEncrypt</span> ### <span id="AesOfbEncrypt">AesOfbEncrypt</span>
<p>Enecrypt data with key use AES OFB algorithm. Length of `key` param should be 16, 24 or 32.</p> <p>Enecrypt data with key use AES OFB algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -298,15 +317,18 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefghijklmnop" key := "abcdefghijklmnop"
encrypted := cryptor.AesOfbEncrypt([]byte(data), []byte(key)) encrypted := cryptor.AesOfbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted)) decrypted := cryptor.AesCfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="AesCfbDecrypt">AesOfbDecrypt</span> ### <span id="AesCfbDecrypt">AesOfbDecrypt</span>
<p>Decrypt data with key use AES OFB algorithm. Length of `key` param should be 16, 24 or 32.</p> <p>Decrypt data with key use AES OFB algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -328,17 +350,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefghijklmnop" key := "abcdefghijklmnop"
encrypted := cryptor.AesOfbEncrypt([]byte(data), []byte(key)) encrypted := cryptor.AesOfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesOfbDecrypt(encrypted, []byte(key)) decrypted := cryptor.AesCfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="Base64StdEncode">Base64StdEncode</span> ### <span id="Base64StdEncode">Base64StdEncode</span>
<p>Encode string with base64 encoding.</p> <p>Encode string with base64 encoding.</p>
@@ -359,13 +383,13 @@ import (
) )
func main() { func main() {
base64Str := cryptor.Base64StdEncode("hello world") base64Str := cryptor.Base64StdEncode("hello")
fmt.Println(base64Str) //aGVsbG8gd29ybGQ= fmt.Println(base64Str)
// Output:
// aGVsbG8=
} }
``` ```
### <span id="Base64StdDecode">Base64StdDecode</span> ### <span id="Base64StdDecode">Base64StdDecode</span>
<p>Decode a base64 encoded string.</p> <p>Decode a base64 encoded string.</p>
@@ -387,13 +411,14 @@ import (
) )
func main() { func main() {
str := cryptor.Base64StdDecode("aGVsbG8gd29ybGQ=") str := cryptor.Base64StdDecode("aGVsbG8=")
fmt.Println(str) //hello world fmt.Println(str)
// Output:
// hello
} }
``` ```
### <span id="DesEcbEncrypt">DesEcbEncrypt</span> ### <span id="DesEcbEncrypt">DesEcbEncrypt</span>
<p>Encrypt data with key use DES ECB algorithm. Length of `key` param should be 8.</p> <p>Encrypt data with key use DES ECB algorithm. Length of `key` param should be 8.</p>
@@ -415,16 +440,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefgh" key := "abcdefgh"
encrypted := cryptor.DesEcbEncrypt([]byte(data), []byte(key)) encrypted := cryptor.DesEcbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted)) decrypted := cryptor.DesEcbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="DesEcbDecrypt">DesEcbDecrypt</span> ### <span id="DesEcbDecrypt">DesEcbDecrypt</span>
<p>Decrypt data with key use DES ECB algorithm. Length of `key` param should be 8.</p> <p>Decrypt data with key use DES ECB algorithm. Length of `key` param should be 8.</p>
@@ -446,17 +474,20 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefgh" key := "abcdefgh"
encrypted := cryptor.DesEcbEncrypt([]byte(data), []byt(key)
encrypted := cryptor.DesEcbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.DesEcbDecrypt(encrypted, []byte(key)) decrypted := cryptor.DesEcbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="DesCbcEncrypt">DesCbcEncrypt</span> ### <span id="DesCbcEncrypt">DesCbcEncrypt</span>
<p>Encrypt data with key use DES CBC algorithm. Length of `key` param should be 8.</p> <p>Encrypt data with key use DES CBC algorithm. Length of `key` param should be 8.</p>
@@ -478,16 +509,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefgh" key := "abcdefgh"
encrypted := cryptor.DesCbcEncrypt([]byte(data), []byt(key)
fmt.Println(string(encrypted)) encrypted := cryptor.DesCbcEncrypt([]byte(data), []byte(key))
decrypted := cryptor.DesCbcDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="DesCbcDecrypt">DesCbcDecrypt</span> ### <span id="DesCbcDecrypt">DesCbcDecrypt</span>
<p>Decrypt data with key use DES CBC algorithm. Length of `key` param should be 8.</p> <p>Decrypt data with key use DES CBC algorithm. Length of `key` param should be 8.</p>
@@ -509,17 +543,18 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefgh" key := "abcdefgh"
encrypted := cryptor.DesCbcEncrypt([]byte(data), []byt(key)
decrypted := cryptor.DesCbcDecrypt(encrypted, []byte(key)) encrypted := cryptor.DesCbcEncrypt([]byte(data), []byte(key))
decrypted := cryptor.DesCbcDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="DesCtrCrypt">DesCtrCrypt</span> ### <span id="DesCtrCrypt">DesCtrCrypt</span>
<p>Encrypt or decrypt data with key use DES CTR algorithm. Length of `key` param should be 8.</p> <p>Encrypt or decrypt data with key use DES CTR algorithm. Length of `key` param should be 8.</p>
@@ -541,17 +576,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefgh" key := "abcdefgh"
encrypted := cryptor.DesCtrCrypt([]byte(data), []byte(key)) encrypted := cryptor.DesCtrCrypt([]byte(data), []byte(key))
decrypted := cryptor.DesCtrCrypt(encrypted, []byte(key)) decrypted := cryptor.DesCtrCrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="DesCfbEncrypt">DesCfbEncrypt</span> ### <span id="DesCfbEncrypt">DesCfbEncrypt</span>
<p>Encrypt data with key use DES CFB algorithm. Length of `key` param should be 8.</p> <p>Encrypt data with key use DES CFB algorithm. Length of `key` param should be 8.</p>
@@ -573,15 +610,18 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefgh" key := "abcdefgh"
encrypted := cryptor.DesCfbEncrypt([]byte(data), []byt(key)
fmt.Println(string(encrypted)) encrypted := cryptor.DesCfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.DesCfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="DesCfbDecrypt">DesCfbDecrypt</span> ### <span id="DesCfbDecrypt">DesCfbDecrypt</span>
<p>Decrypt data with key use DES CBC algorithm. Length of `key` param should be 8.</p> <p>Decrypt data with key use DES CBC algorithm. Length of `key` param should be 8.</p>
@@ -603,16 +643,18 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefgh" key := "abcdefgh"
encrypted := cryptor.DesCfbEncrypt([]byte(data), []byt(key)
encrypted := cryptor.DesCfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.DesCfbDecrypt(encrypted, []byte(key)) decrypted := cryptor.DesCfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="DesOfbEncrypt">DesOfbEncrypt</span> ### <span id="DesOfbEncrypt">DesOfbEncrypt</span>
<p>Enecrypt data with key use DES OFB algorithm. Length of `key` param should be 8.</p> <p>Enecrypt data with key use DES OFB algorithm. Length of `key` param should be 8.</p>
@@ -634,15 +676,18 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefgh" key := "abcdefgh"
encrypted := cryptor.DesOfbEncrypt([]byte(data), []byte(key)) encrypted := cryptor.DesOfbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted)) decrypted := cryptor.DesOfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="DesOfbDecrypt">DesOfbDecrypt</span> ### <span id="DesOfbDecrypt">DesOfbDecrypt</span>
<p>Decrypt data with key use DES OFB algorithm. Length of `key` param should be 8.</p> <p>Decrypt data with key use DES OFB algorithm. Length of `key` param should be 8.</p>
@@ -664,17 +709,19 @@ import (
) )
func main() { func main() {
data := "hello world" data := "hello"
key := "abcdefgh" key := "abcdefgh"
encrypted := cryptor.DesOfbEncrypt([]byte(data), []byte(key)) encrypted := cryptor.DesOfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.DesOfbDecrypt(encrypted, []byte(key)) decrypted := cryptor.DesOfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="HmacMd5">HmacMd5</span> ### <span id="HmacMd5">HmacMd5</span>
<p>Get the md5 hmac hash of string.</p> <p>Get the md5 hmac hash of string.</p>
@@ -696,13 +743,16 @@ import (
) )
func main() { func main() {
s := cryptor.HmacMd5("hello world", "12345")) str := "hello"
fmt.Println(s) //5f4c9faaff0a1ad3007d9ddc06abe36d key := "12345"
hms := cryptor.HmacMd5(str, key)
fmt.Println(hms)
// Output:
// e834306eab892d872525d4918a7a639a
} }
``` ```
### <span id="HmacSha1">HmacSha1</span> ### <span id="HmacSha1">HmacSha1</span>
<p>Get the sha1 hmac hash of string.</p> <p>Get the sha1 hmac hash of string.</p>
@@ -724,13 +774,16 @@ import (
) )
func main() { func main() {
s := cryptor.HmacSha1("hello world", "12345")) str := "hello"
fmt.Println(s) //3826f812255d8683f051ee97346d1359234d5dbd key := "12345"
hms := cryptor.HmacSha1(str, key)
fmt.Println(hms)
// Output:
// 5c6a9db0cccb92e36ed0323fd09b7f936de9ace0
} }
``` ```
### <span id="HmacSha256">HmacSha256</span> ### <span id="HmacSha256">HmacSha256</span>
<p>Get the sha256 hmac hash of string</p> <p>Get the sha256 hmac hash of string</p>
@@ -752,13 +805,17 @@ import (
) )
func main() { func main() {
s := cryptor.HmacSha256("hello world", "12345")) str := "hello"
fmt.Println(s) //9dce2609f2d67d41f74c7f9efc8ccd44370d41ad2de52982627588dfe7289ab8 key := "12345"
hms := cryptor.HmacSha256(str, key)
fmt.Println(hms)
// Output:
// 315bb93c4e989862ba09cb62e05d73a5f376cb36f0d786edab0c320d059fde75
} }
``` ```
### <span id="HmacSha512">HmacSha512</span> ### <span id="HmacSha512">HmacSha512</span>
<p>Get the sha512 hmac hash of string.</p> <p>Get the sha512 hmac hash of string.</p>
@@ -780,14 +837,18 @@ import (
) )
func main() { func main() {
s := cryptor.HmacSha512("hello world", "12345")) str := "hello"
fmt.Println(s) key := "12345"
//5b1563ac4e9b49c9ada8ccb232588fc4f0c30fd12f756b3a0b95af4985c236ca60925253bae10ce2c6bf9af1c1679b51e5395ff3d2826c0a2c7c0d72225d4175
hms := cryptor.HmacSha512(str, key)
fmt.Println(hms)
// Output:
// dd8f1290a9dd23d354e2526d9a2e9ce8cffffdd37cb320800d1c6c13d2efc363288376a196c5458daf53f8e1aa6b45a6d856303d5c0a2064bff9785861d48cfc
} }
``` ```
### <span id="Md5String">Md5String</span> ### <span id="Md5String">Md5String</span>
<p>Get the md5 value of string.</p> <p>Get the md5 value of string.</p>
@@ -809,13 +870,16 @@ import (
) )
func main() { func main() {
s := cryptor.Md5String("hello")) str := "hello"
fmt.Println(s) //5d41402abc4b2a76b9719d911017c592
md5Str := cryptor.Md5String(str)
fmt.Println(md5Str)
// Output:
// 5d41402abc4b2a76b9719d911017c592
} }
``` ```
### <span id="Md5File">Md5File</span> ### <span id="Md5File">Md5File</span>
<p>Get the md5 value of file.</p> <p>Get the md5 value of file.</p>
@@ -842,8 +906,6 @@ func main() {
} }
``` ```
### <span id="Sha1">Sha1</span> ### <span id="Sha1">Sha1</span>
<p>Get the sha1 value of string.</p> <p>Get the sha1 value of string.</p>
@@ -865,13 +927,16 @@ import (
) )
func main() { func main() {
s := cryptor.Sha1("hello world")) str := "hello"
fmt.Println(s) //2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
result := cryptor.Sha1(str)
fmt.Println(result)
// Output:
// aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
} }
``` ```
### <span id="Sha256">Sha256</span> ### <span id="Sha256">Sha256</span>
<p>Get the sha256 value of string.</p> <p>Get the sha256 value of string.</p>
@@ -893,13 +958,16 @@ import (
) )
func main() { func main() {
s := cryptor.Sha256("hello world")) str := "hello"
fmt.Println(s) //b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
result := cryptor.Sha256(str)
fmt.Println(result)
// Output:
// 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
} }
``` ```
### <span id="Sha512">Sha512</span> ### <span id="Sha512">Sha512</span>
<p>Get the sha512 value of string.</p> <p>Get the sha512 value of string.</p>
@@ -921,13 +989,16 @@ import (
) )
func main() { func main() {
s := cryptor.Sha512("hello world")) str := "hello"
fmt.Println(s) //309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f
result := cryptor.Sha512(str)
fmt.Println(result)
// Output:
// 9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043
} }
``` ```
### <span id="GenerateRsaKey">GenerateRsaKey</span> ### <span id="GenerateRsaKey">GenerateRsaKey</span>
<p>Create the rsa public and private key file in current directory.</p> <p>Create the rsa public and private key file in current directory.</p>
@@ -956,8 +1027,6 @@ func main() {
} }
``` ```
### <span id="RsaEncrypt">RsaEncrypt</span> ### <span id="RsaEncrypt">RsaEncrypt</span>
<p>Encrypt data with public key file useing ras algorithm.</p> <p>Encrypt data with public key file useing ras algorithm.</p>
@@ -981,19 +1050,21 @@ import (
func main() { func main() {
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem") err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
if err != nil { if err != nil {
fmt.Println(err) return
} }
data := []byte("hello world") data := []byte("hello")
encrypted := cryptor.RsaEncrypt(data, "rsa_public.pem") encrypted := cryptor.RsaEncrypt(data, "rsa_public.pem")
decrypted := cryptor.RsaDecrypt(encrypted, "rsa_private.pem") decrypted := cryptor.RsaDecrypt(encrypted, "rsa_private.pem")
fmt.Println(string(decrypted)) //hello world fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```
### <span id="RsaDecrypt">RsaDecrypt</span> ### <span id="RsaDecrypt">RsaDecrypt</span>
<p>Decrypt data with private key file useing ras algorithm.</p> <p>Decrypt data with private key file useing ras algorithm.</p>
@@ -1017,14 +1088,17 @@ import (
func main() { func main() {
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem") err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
if err != nil { if err != nil {
fmt.Println(err) return
} }
data := []byte("hello world") data := []byte("hello")
encrypted := cryptor.RsaEncrypt(data, "rsa_public.pem") encrypted := cryptor.RsaEncrypt(data, "rsa_public.pem")
decrypted := cryptor.RsaDecrypt(encrypted, "rsa_private.pem") decrypted := cryptor.RsaDecrypt(encrypted, "rsa_private.pem")
fmt.Println(string(decrypted)) //hello world fmt.Println(string(decrypted))
// Output:
// hello
} }
``` ```

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +1,18 @@
# Datetime # Datetime
Package datetime supports date and time format and compare. Package datetime supports date and time format and compare.
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Source: ## Source:
- [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)
- [https://github.com/duke-git/lancet/blob/main/datetime/conversion.go](https://github.com/duke-git/lancet/blob/main/datetime/conversion.go) - [https://github.com/duke-git/lancet/blob/main/datetime/conversion.go](https://github.com/duke-git/lancet/blob/main/datetime/conversion.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Usage: ## Usage:
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/datetime" "github.com/duke-git/lancet/v2/datetime"
@@ -20,66 +22,67 @@ import (
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Index ## Index
- [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)
- [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)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Documentation ## Documentation
## Note: ## Note:
1. 'format' string param in func FormatTimeToStr and FormatStrToTime function should be one of flows:
- 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. 'format' string param in func FormatTimeToStr and FormatStrToTime function should be one of flows:
- 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> ### <span id="AddDay">AddDay</span>
<p>Add or sub days to time.</p> <p>Add or sub days to time.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -87,6 +90,7 @@ import (
```go ```go
func AddDay(t time.Time, day int64) time.Time func AddDay(t time.Time, day int64) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -100,15 +104,24 @@ import (
func main() { func main() {
now := time.Now() now := time.Now()
after2Days := datetime.AddDay(now, 2)
before2Days := datetime.AddDay(now, -2)
fmt.Println(after2Days, before2Days) tomorrow := datetime.AddDay(now, 1)
diff1 := tomorrow.Sub(now)
yesterday := datetime.AddDay(now, -1)
diff2 := yesterday.Sub(now)
fmt.Println(diff1)
fmt.Println(diff2)
// Output:
// 24h0m0s
// -24h0m0s
} }
``` ```
### <span id="AddHour">AddHour</span> ### <span id="AddHour">AddHour</span>
<p>Add or sub hours to time.</p> <p>Add or sub hours to time.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -116,6 +129,7 @@ func main() {
```go ```go
func AddHour(t time.Time, hour int64) time.Time func AddHour(t time.Time, hour int64) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -129,14 +143,24 @@ import (
func main() { func main() {
now := time.Now() now := time.Now()
after2Hours := datetime.AddHour(now, 2)
before2Hours := datetime.AddHour(now, -2)
fmt.Println(after2Hours, after2Hours) after2Hours := datetime.AddHour(now, 2)
diff1 := after2Hours.Sub(now)
before2Hours := datetime.AddHour(now, -2)
diff2 := before2Hours.Sub(now)
fmt.Println(diff1)
fmt.Println(diff2)
// Output:
// 2h0m0s
// -2h0m0s
} }
``` ```
### <span id="AddMinute">AddMinute</span> ### <span id="AddMinute">AddMinute</span>
<p>Add or sub minutes to time.</p> <p>Add or sub minutes to time.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -144,6 +168,7 @@ func main() {
```go ```go
func AddMinute(t time.Time, minute int64) time.Time func AddMinute(t time.Time, minute int64) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -157,14 +182,24 @@ import (
func main() { func main() {
now := time.Now() now := time.Now()
after2Minute := datetime.AddMinute(now, 2)
before2Minute := datetime.AddMinute(now, -2)
fmt.Println(after2Minute, before2Minute) after2Minutes := datetime.AddMinute(now, 2)
diff1 := after2Minutes.Sub(now)
before2Minutes := datetime.AddMinute(now, -2)
diff2 := before2Minutes.Sub(now)
fmt.Println(diff1)
fmt.Println(diff2)
// Output:
// 2m0s
// -2m0s
} }
``` ```
### <span id="BeginOfMinute">BeginOfMinute</span> ### <span id="BeginOfMinute">BeginOfMinute</span>
<p>Return beginning minute time of day.</p> <p>Return beginning minute time of day.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -172,6 +207,7 @@ func main() {
```go ```go
func BeginOfMinute(t time.Time) time.Time func BeginOfMinute(t time.Time) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -184,13 +220,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.BeginOfMinute(td) result := datetime.BeginOfMinute(input)
fmt.Println(bm) //2022-02-15 15:48:00 +0800 CST
fmt.Println(result)
// Output:
// 2023-01-08 18:50:00 +0000 UTC
} }
``` ```
### <span id="BeginOfHour">BeginOfHour</span> ### <span id="BeginOfHour">BeginOfHour</span>
<p>Return zero time of day.</p> <p>Return zero time of day.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -198,6 +239,7 @@ func main() {
```go ```go
func BeginOfHour(t time.Time) time.Time func BeginOfHour(t time.Time) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -210,13 +252,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.BeginOfHour(td) result := datetime.BeginOfHour(input)
fmt.Println(bm) //2022-02-15 15:00:00 +0800 CST
fmt.Println(result)
// Output:
// 2023-01-08 18:00:00 +0000 UTC
} }
``` ```
### <span id="BeginOfDay">BeginOfDay</span> ### <span id="BeginOfDay">BeginOfDay</span>
<p>Return begin time of day.</p> <p>Return begin time of day.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -224,6 +271,7 @@ func main() {
```go ```go
func BeginOfDay(t time.Time) time.Time func BeginOfDay(t time.Time) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -236,15 +284,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.BeginOfDay(td) result := datetime.BeginOfDay(input)
fmt.Println(bm) //2022-02-15 00:00:00 +0800 CST
fmt.Println(result)
// Output:
// 2023-01-08 00:00:00 +0000 UTC
} }
``` ```
### <span id="BeginOfWeek">BeginOfWeek</span> ### <span id="BeginOfWeek">BeginOfWeek</span>
<p>Return beginning time of week, week begin from Sunday.</p> <p>Return beginning time of week, week begin from Sunday.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -252,6 +303,7 @@ func main() {
```go ```go
func BeginOfWeek(t time.Time, beginFrom ...time.Weekday) time.Time func BeginOfWeek(t time.Time, beginFrom ...time.Weekday) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -264,15 +316,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.BeginOfWeek(td) result := datetime.BeginOfWeek(input)
fmt.Println(bm) //2022-02-13 00:00:00 +0800 CST
fmt.Println(result)
// Output:
// 2023-01-08 00:00:00 +0000 UTC
} }
``` ```
### <span id="BeginOfMonth">BeginOfMonth</span> ### <span id="BeginOfMonth">BeginOfMonth</span>
<p>Return beginning time of month</p> <p>Return beginning time of month</p>
<b>Signature:</b> <b>Signature:</b>
@@ -280,6 +335,7 @@ func main() {
```go ```go
func BeginOfMonth(t time.Time) time.Time func BeginOfMonth(t time.Time) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -292,14 +348,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.BeginOfMonth(td) result := datetime.BeginOfMonth(input)
fmt.Println(bm) //2022-02-01 00:00:00 +0800 CST
fmt.Println(result)
// Output:
// 2023-01-01 00:00:00 +0000 UTC
} }
``` ```
### <span id="BeginOfYear">BeginOfYear</span> ### <span id="BeginOfYear">BeginOfYear</span>
<p>Return beginning time of year.</p> <p>Return beginning time of year.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -307,6 +367,7 @@ func main() {
```go ```go
func BeginOfYear(t time.Time) time.Time func BeginOfYear(t time.Time) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -319,15 +380,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.BeginOfYear(td) result := datetime.BeginOfYear(input)
fmt.Println(bm) //2022-01-01 00:00:00 +0800 CST
fmt.Println(result)
// Output:
// 2023-01-01 00:00:00 +0000 UTC
} }
``` ```
### <span id="EndOfMinute">EndOfMinute</span> ### <span id="EndOfMinute">EndOfMinute</span>
<p>Return end time minute of day.</p> <p>Return end time minute of day.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -335,6 +399,7 @@ func main() {
```go ```go
func EndOfMinute(t time.Time) time.Time func EndOfMinute(t time.Time) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -347,13 +412,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.EndOfMinute(td) result := datetime.EndOfMinute(input)
fmt.Println(bm) //2022-02-15 15:48:59.999999999 +0800 CST
fmt.Println(result)
// Output:
// 2023-01-08 18:50:59.999999999 +0000 UTC
} }
``` ```
### <span id="EndOfHour">EndOfHour</span> ### <span id="EndOfHour">EndOfHour</span>
<p>Return end time hour of day.</p> <p>Return end time hour of day.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -361,6 +431,7 @@ func main() {
```go ```go
func EndOfHour(t time.Time) time.Time func EndOfHour(t time.Time) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -373,13 +444,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.EndOfHour(td) result := datetime.EndOfHour(input)
fmt.Println(bm) //2022-02-15 15:59:59.999999999 +0800 CST
fmt.Println(result)
// Output:
// 2023-01-08 18:59:59.999999999 +0000 UTC
} }
``` ```
### <span id="EndOfDay">EndOfDay</span> ### <span id="EndOfDay">EndOfDay</span>
<p>Return end time hour of day.</p> <p>Return end time hour of day.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -387,6 +463,7 @@ func main() {
```go ```go
func EndOfDay(t time.Time) time.Time func EndOfDay(t time.Time) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -399,15 +476,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.EndOfDay(td) result := datetime.EndOfDay(input)
fmt.Println(bm) //2022-02-15 23:59:59.999999999 +0800 CST
fmt.Println(result)
// Output:
// 2023-01-08 23:59:59.999999999 +0000 UTC
} }
``` ```
### <span id="EndOfWeek">EndOfWeek</span> ### <span id="EndOfWeek">EndOfWeek</span>
<p>Return end time of week, week end with Saturday.</p> <p>Return end time of week, week end with Saturday.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -415,6 +495,7 @@ func main() {
```go ```go
func EndOfWeek(t time.Time, endWith ...time.Weekday) time.Time func EndOfWeek(t time.Time, endWith ...time.Weekday) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -427,15 +508,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.EndOfWeek(td) result := datetime.EndOfWeek(input)
fmt.Println(bm) //2022-02-19 23:59:59.999999999 +0800 CST
fmt.Println(result)
// Output:
// 2023-01-14 23:59:59.999999999 +0000 UTC
} }
``` ```
### <span id="EndOfMonth">EndOfMonth</span> ### <span id="EndOfMonth">EndOfMonth</span>
<p>Return end time of month</p> <p>Return end time of month</p>
<b>Signature:</b> <b>Signature:</b>
@@ -443,6 +527,7 @@ func main() {
```go ```go
func EndOfMonth(t time.Time) time.Time func EndOfMonth(t time.Time) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -455,14 +540,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.EndOfMonth(td) result := datetime.EndOfMonth(input)
fmt.Println(bm) //2022-02-28 23:59:59.999999999 +0800 CST
fmt.Println(result)
// Output:
// 2023-01-31 23:59:59.999999999 +0000 UTC
} }
``` ```
### <span id="EndOfYear">EndOfYear</span> ### <span id="EndOfYear">EndOfYear</span>
<p>Return beginning time of year.</p> <p>Return beginning time of year.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -470,6 +559,7 @@ func main() {
```go ```go
func EndOfYear(t time.Time) time.Time func EndOfYear(t time.Time) time.Time
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -482,14 +572,18 @@ import (
) )
func main() { func main() {
td := time.Date(2022, 2, 15, 15, 48, 40, 112, time.Local) input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC)
bm := datetime.EndOfYear(td) result := datetime.EndOfYear(input)
fmt.Println(bm) //2022-12-31 23:59:59.999999999 +0800 CST
fmt.Println(result)
// Output:
// 2023-12-31 23:59:59.999999999 +0000 UTC
} }
``` ```
### <span id="GetNowDate">GetNowDate</span> ### <span id="GetNowDate">GetNowDate</span>
<p>Get current date string, format is yyyy-mm-dd.</p> <p>Get current date string, format is yyyy-mm-dd.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -497,6 +591,7 @@ func main() {
```go ```go
func GetNowDate() string func GetNowDate() string
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -511,12 +606,16 @@ import (
func main() { func main() {
now := time.Now() now := time.Now()
currentDate := datetime.GetNowDate() currentDate := datetime.GetNowDate()
fmt.Println(currentDate) // 2022-01-28
fmt.Println(currentDate)
// Output:
// 2022-01-28
} }
``` ```
### <span id="GetNowTime">GetNowTime</span> ### <span id="GetNowTime">GetNowTime</span>
<p>Get current time string, format is hh:mm:ss.</p> <p>Get current time string, format is hh:mm:ss.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -524,6 +623,7 @@ func main() {
```go ```go
func GetNowTime() string func GetNowTime() string
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -538,12 +638,16 @@ import (
func main() { func main() {
now := time.Now() now := time.Now()
currentTime := datetime.GetNowTime() currentTime := datetime.GetNowTime()
fmt.Println(currentDate) // 15:57:33
fmt.Println(currentTime) // 15:57:33
// Output:
// 15:57:33
} }
``` ```
### <span id="GetNowDateTime">GetNowDateTime</span> ### <span id="GetNowDateTime">GetNowDateTime</span>
<p>Get current date time string, format is yyyy-mm-dd hh:mm:ss.</p> <p>Get current date time string, format is yyyy-mm-dd hh:mm:ss.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -551,6 +655,7 @@ func main() {
```go ```go
func GetNowDateTime() string func GetNowDateTime() string
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -565,12 +670,16 @@ import (
func main() { func main() {
now := time.Now() now := time.Now()
current := datetime.GetNowDateTime() current := datetime.GetNowDateTime()
fmt.Println(current) // 2022-01-28 15:59:33
fmt.Println(current)
// Output:
// 2022-01-28 15:59:33
} }
``` ```
### <span id="GetZeroHourTimestamp">GetZeroHourTimestamp</span> ### <span id="GetZeroHourTimestamp">GetZeroHourTimestamp</span>
<p>Return timestamp of zero hour (timestamp of 00:00).</p> <p>Return timestamp of zero hour (timestamp of 00:00).</p>
<b>Signature:</b> <b>Signature:</b>
@@ -578,6 +687,7 @@ func main() {
```go ```go
func GetZeroHourTimestamp() int64 func GetZeroHourTimestamp() int64
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -592,12 +702,16 @@ import (
func main() { func main() {
now := time.Now() now := time.Now()
zeroTime := datetime.GetZeroHourTimestamp() zeroTime := datetime.GetZeroHourTimestamp()
fmt.Println(zeroTime) // 1643299200
fmt.Println(zeroTime)
// Output:
// 1643299200
} }
``` ```
### <span id="GetNightTimestamp">GetNightTimestamp</span> ### <span id="GetNightTimestamp">GetNightTimestamp</span>
<p>Return timestamp of zero hour (timestamp of 23:59).</p> <p>Return timestamp of zero hour (timestamp of 23:59).</p>
<b>Signature:</b> <b>Signature:</b>
@@ -605,6 +719,7 @@ func main() {
```go ```go
func GetNightTimestamp() int64 func GetNightTimestamp() int64
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -619,11 +734,16 @@ import (
func main() { func main() {
now := time.Now() now := time.Now()
nightTime := datetime.GetNightTimestamp() nightTime := datetime.GetNightTimestamp()
fmt.Println(nightTime) // 1643385599
fmt.Println(nightTime)
// Output:
// 1643385599
} }
``` ```
### <span id="FormatTimeToStr">FormatTimeToStr</span> ### <span id="FormatTimeToStr">FormatTimeToStr</span>
<p>Format time to string, `format` param specification see note 1.</p> <p>Format time to string, `format` param specification see note 1.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -631,6 +751,7 @@ func main() {
```go ```go
func FormatTimeToStr(t time.Time, format string) string func FormatTimeToStr(t time.Time, format string) string
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -643,14 +764,25 @@ import (
) )
func main() { func main() {
now := time.Now() t, _ := time.Parse("2006-01-02 15:04:05", "2021-01-02 16:04:08")
timeStr := datetime.FormatTimeToStr(now, "yyyy/mm/dd hh:mm:ss")
fmt.Println(timeStr) //2022/01/28 16:07:44 result1 := datetime.FormatTimeToStr(t, "yyyy-mm-dd hh:mm:ss")
result2 := datetime.FormatTimeToStr(t, "yyyy-mm-dd")
result3 := datetime.FormatTimeToStr(t, "dd-mm-yy hh:mm:ss")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 2021-01-02 16:04:08
// 2021-01-02
// 02-01-21 16:04:08
} }
``` ```
### <span id="FormatStrToTime">FormatStrToTime</span> ### <span id="FormatStrToTime">FormatStrToTime</span>
<p>Format string to time, `format` param specification see note 1.</p> <p>Format string to time, `format` param specification see note 1.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -658,6 +790,7 @@ func main() {
```go ```go
func FormatStrToTime(str, format string) (time.Time, error) func FormatStrToTime(str, format string) (time.Time, error)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -669,24 +802,34 @@ import (
) )
func main() { func main() {
time := datetime.FormatStrToTime("2006-01-02 15:04:05", "yyyy/mm/dd hh:mm:ss") result1, _ := datetime.FormatStrToTime("2021-01-02 16:04:08", "yyyy-mm-dd hh:mm:ss")
fmt.Println(time) result2, _ := datetime.FormatStrToTime("2021-01-02", "yyyy-mm-dd")
result3, _ := datetime.FormatStrToTime("02-01-21 16:04:08", "dd-mm-yy hh:mm:ss")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 2021-01-02 16:04:08 +0000 UTC
// 2021-01-02 00:00:00 +0000 UTC
// 2021-01-02 16:04:08 +0000 UTC
} }
``` ```
### <span id="NewUnixNow">NewUnixNow</span> ### <span id="NewUnixNow">NewUnixNow</span>
<p>Return unix timestamp of current time</p> <p>Return unix timestamp of current time</p>
<b>Signature:</b> <b>Signature:</b>
```go ```go
type theTime struct { type theTime struct {
unix int64 unix int64
} }
func NewUnixNow() *theTime func NewUnixNow() *theTime
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -699,12 +842,15 @@ import (
func main() { func main() {
tm := datetime.NewUnixNow() tm := datetime.NewUnixNow()
fmt.Println(tm) //&{1647597438} fmt.Println(tm)
// Output:
// &{1647597438}
} }
``` ```
### <span id="NewUnix">NewUnix</span> ### <span id="NewUnix">NewUnix</span>
<p>Return unix timestamp of specified int64 value.</p> <p>Return unix timestamp of specified int64 value.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -715,6 +861,7 @@ type theTime struct {
} }
func NewUnix(unix int64) *theTime func NewUnix(unix int64) *theTime
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -727,13 +874,15 @@ import (
func main() { func main() {
tm := datetime.NewUnix(1647597438) tm := datetime.NewUnix(1647597438)
fmt.Println(tm) //&{1647597438} fmt.Println(tm)
// Output:
// &{1647597438}
} }
``` ```
### <span id="NewFormat">NewFormat</span> ### <span id="NewFormat">NewFormat</span>
<p>Return unix timestamp of specified time string, t should be "yyyy-mm-dd hh:mm:ss".</p> <p>Return unix timestamp of specified time string, t should be "yyyy-mm-dd hh:mm:ss".</p>
<b>Signature:</b> <b>Signature:</b>
@@ -744,6 +893,7 @@ type theTime struct {
} }
func NewFormat(t string) (*theTime, error) func NewFormat(t string) (*theTime, error)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -756,14 +906,15 @@ import (
func main() { func main() {
tm, err := datetime.NewFormat("2022-03-18 17:04:05") tm, err := datetime.NewFormat("2022-03-18 17:04:05")
fmt.Println(tm) //&{1647594245} fmt.Println(tm)
// Output:
// &{1647594245}
} }
``` ```
### <span id="NewISO8601">NewISO8601</span> ### <span id="NewISO8601">NewISO8601</span>
<p>Return unix timestamp of specified iso8601 time string.</p> <p>Return unix timestamp of specified iso8601 time string.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -774,6 +925,7 @@ type theTime struct {
} }
func NewISO8601(iso8601 string) (*theTime, error) func NewISO8601(iso8601 string) (*theTime, error)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -786,13 +938,15 @@ import (
func main() { func main() {
tm, err := datetime.NewISO8601("2006-01-02T15:04:05.999Z") tm, err := datetime.NewISO8601("2006-01-02T15:04:05.999Z")
fmt.Println(tm) //&{1136214245} fmt.Println(tm)
// Output:
// &{1136214245}
} }
``` ```
### <span id="ToUnix">ToUnix</span> ### <span id="ToUnix">ToUnix</span>
<p>Return unix timestamp.</p> <p>Return unix timestamp.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -800,6 +954,7 @@ func main() {
```go ```go
func (t *theTime) ToUnix() int64 func (t *theTime) ToUnix() int64
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -812,13 +967,15 @@ import (
func main() { func main() {
tm := datetime.NewUnixNow() tm := datetime.NewUnixNow()
fmt.Println(tm.ToUnix()) //1647597438 fmt.Println(tm.ToUnix())
// Output:
// 1647597438
} }
``` ```
### <span id="ToFormat">ToFormat</span> ### <span id="ToFormat">ToFormat</span>
<p>Return time string 'yyyy-mm-dd hh:mm:ss'.</p> <p>Return time string 'yyyy-mm-dd hh:mm:ss'.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -826,6 +983,7 @@ func main() {
```go ```go
func (t *theTime) ToFormat() string func (t *theTime) ToFormat() string
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -838,13 +996,15 @@ import (
func main() { func main() {
tm, _ := datetime.NewFormat("2022-03-18 17:04:05") tm, _ := datetime.NewFormat("2022-03-18 17:04:05")
fmt.Println(tm.ToFormat()) //"2022-03-18 17:04:05" fmt.Println(tm.ToFormat())
// Output:
// 2022-03-18 17:04:05
} }
``` ```
### <span id="ToFormatForTpl">ToFormatForTpl</span> ### <span id="ToFormatForTpl">ToFormatForTpl</span>
<p>Return the time string which format is specified tpl.</p> <p>Return the time string which format is specified tpl.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -852,6 +1012,7 @@ func main() {
```go ```go
func (t *theTime) ToFormatForTpl(tpl string) string func (t *theTime) ToFormatForTpl(tpl string) string
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -865,12 +1026,15 @@ import (
func main() { func main() {
tm, _ := datetime.NewFormat("2022-03-18 17:04:05") tm, _ := datetime.NewFormat("2022-03-18 17:04:05")
ts := tm.ToFormatForTpl("2006/01/02 15:04:05") ts := tm.ToFormatForTpl("2006/01/02 15:04:05")
fmt.Println(ts) //"2022/03/18 17:04:05" fmt.Println(ts)
// Output:
// 2022/03/18 17:04:05
} }
``` ```
### <span id="ToIso8601">ToIso8601</span> ### <span id="ToIso8601">ToIso8601</span>
<p>Return iso8601 time string.</p> <p>Return iso8601 time string.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -878,6 +1042,7 @@ func main() {
```go ```go
func (t *theTime) ToIso8601() string func (t *theTime) ToIso8601() string
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -891,6 +1056,9 @@ import (
func main() { func main() {
tm, _ := datetime.NewISO8601("2006-01-02T15:04:05.999Z") tm, _ := datetime.NewISO8601("2006-01-02T15:04:05.999Z")
ts := tm.ToIso8601() ts := tm.ToIso8601()
fmt.Println(ts) //"2006-01-02T23:04:05+08:00" fmt.Println(ts)
// Output:
// 2006-01-02T23:04:05+08:00
} }
``` ```

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +1,17 @@
# Fileutil # Fileutil
Package fileutil implements some basic functions for file operations. Package fileutil implements some basic functions for file operations.
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Source: ## Source:
- [https://github.com/duke-git/lancet/blob/main/fileutil/file.go](https://github.com/duke-git/lancet/blob/main/fileutil/file.go) - [https://github.com/duke-git/lancet/blob/main/fileutil/file.go](https://github.com/duke-git/lancet/blob/main/fileutil/file.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Usage: ## Usage:
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/fileutil" "github.com/duke-git/lancet/v2/fileutil"
@@ -19,30 +21,30 @@ import (
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Index ## Index
- [ClearFile](#ClearFile)
- [CreateFile](#CreateFile) - [ClearFile](#ClearFile)
- [CreateDir](#CreateDir) - [CreateFile](#CreateFile)
- [CopyFile](#CopyFile) - [CreateDir](#CreateDir)
- [FileMode](#FileMode) - [CopyFile](#CopyFile)
- [MiMeType](#MiMeType) - [FileMode](#FileMode)
- [IsExist](#IsExist) - [MiMeType](#MiMeType)
- [IsLink](#IsLink) - [IsExist](#IsExist)
- [IsDir](#IsDir) - [IsLink](#IsLink)
- [ListFileNames](#ListFileNames) - [IsDir](#IsDir)
- [RemoveFile](#RemoveFile) - [ListFileNames](#ListFileNames)
- [ReadFileToString](#ReadFileToString) - [RemoveFile](#RemoveFile)
- [ReadFileByLine](#ReadFileByLine) - [ReadFileToString](#ReadFileToString)
- [Zip](#Zip) - [ReadFileByLine](#ReadFileByLine)
- [UnZip](#UnZip) - [Zip](#Zip)
- [UnZip](#UnZip) - [UnZip](#UnZip)
- [UnZip](#UnZip)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Documentation ## Documentation
### <span id="ClearFile">ClearFile</span> ### <span id="ClearFile">ClearFile</span>
<p>Clear the file content, write empty string to the file.</p> <p>Clear the file content, write empty string to the file.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -50,6 +52,7 @@ import (
```go ```go
func ClearFile(path string) error func ClearFile(path string) error
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -69,6 +72,7 @@ func main() {
``` ```
### <span id="CreateFile">CreateFile</span> ### <span id="CreateFile">CreateFile</span>
<p>Create file in path. return true if create succeed.</p> <p>Create file in path. return true if create succeed.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -76,6 +80,7 @@ func main() {
```go ```go
func CreateFile(path string) bool func CreateFile(path string) bool
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -92,9 +97,8 @@ func main() {
} }
``` ```
### <span id="CreateDir">CreateDir</span> ### <span id="CreateDir">CreateDir</span>
<p>Create directory in absolute path. param `absPath` like /a/, /a/b/.</p> <p>Create directory in absolute path. param `absPath` like /a/, /a/b/.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -102,6 +106,7 @@ func main() {
```go ```go
func CreateDir(absPath string) error func CreateDir(absPath string) error
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -118,8 +123,8 @@ func main() {
} }
``` ```
### <span id="CopyFile">CopyFile</span> ### <span id="CopyFile">CopyFile</span>
<p>Copy src file to dest file. If dest file exist will overwrite it.</p> <p>Copy src file to dest file. If dest file exist will overwrite it.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -127,6 +132,7 @@ func main() {
```go ```go
func CopyFile(srcFilePath string, dstFilePath string) error func CopyFile(srcFilePath string, dstFilePath string) error
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -145,9 +151,8 @@ func main() {
} }
``` ```
### <span id="FileMode">FileMode</span> ### <span id="FileMode">FileMode</span>
<p>Return file mode infomation.</p> <p>Return file mode infomation.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -155,6 +160,7 @@ func main() {
```go ```go
func FileMode(path string) (fs.FileMode, error) func FileMode(path string) (fs.FileMode, error)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -174,9 +180,8 @@ func main() {
} }
``` ```
### <span id="MiMeType">MiMeType</span> ### <span id="MiMeType">MiMeType</span>
<p>Get file mime type, 'file' param's type should be string or *os.File.</p> <p>Get file mime type, 'file' param's type should be string or *os.File.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -184,6 +189,7 @@ func main() {
```go ```go
func MiMeType(file any) string func MiMeType(file any) string
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -205,10 +211,8 @@ func main() {
} }
``` ```
### <span id="IsExist">IsExist</span> ### <span id="IsExist">IsExist</span>
<p>Checks if a file or directory exists.</p> <p>Checks if a file or directory exists.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -216,6 +220,7 @@ func main() {
```go ```go
func IsExist(path string) bool func IsExist(path string) bool
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -233,9 +238,8 @@ func main() {
} }
``` ```
### <span id="IsLink">IsLink</span> ### <span id="IsLink">IsLink</span>
<p>Checks if a file is symbol link or not.</p> <p>Checks if a file is symbol link or not.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -243,6 +247,7 @@ func main() {
```go ```go
func IsLink(path string) bool func IsLink(path string) bool
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -259,16 +264,16 @@ func main() {
} }
``` ```
### <span id="IsDir">IsDir</span> ### <span id="IsDir">IsDir</span>
<p>Checks if the path is directy or not.</p> <p>Checks if the path is directy or not.</p>
<b>Signature:</b> <b>Signature:</b>
```go ```go
func IsDir(path string) bool func IsDir(path string) bool
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -288,9 +293,8 @@ func main() {
} }
``` ```
### <span id="ListFileNames">ListFileNames</span> ### <span id="ListFileNames">ListFileNames</span>
<p>List all file names in given path.</p> <p>List all file names in given path.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -298,6 +302,7 @@ func main() {
```go ```go
func ListFileNames(path string) ([]string, error) func ListFileNames(path string) ([]string, error)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -314,9 +319,8 @@ func main() {
} }
``` ```
### <span id="RemoveFile">RemoveFile</span> ### <span id="RemoveFile">RemoveFile</span>
<p>Remove the file of path.</p> <p>Remove the file of path.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -324,6 +328,7 @@ func main() {
```go ```go
func RemoveFile(path string) error func RemoveFile(path string) error
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -342,8 +347,8 @@ func main() {
} }
``` ```
### <span id="ReadFileToString">ReadFileToString</span> ### <span id="ReadFileToString">ReadFileToString</span>
<p>Return string of file content.</p> <p>Return string of file content.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -351,6 +356,7 @@ func main() {
```go ```go
func ReadFileToString(path string) (string, error) func ReadFileToString(path string) (string, error)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -374,9 +380,8 @@ func main() {
} }
``` ```
### <span id="ReadFileByLine">ReadFileByLine</span> ### <span id="ReadFileByLine">ReadFileByLine</span>
<p>Read file line by line, and return slice of lines</p> <p>Read file line by line, and return slice of lines</p>
<b>Signature:</b> <b>Signature:</b>
@@ -384,6 +389,7 @@ func main() {
```go ```go
func ReadFileByLine(path string)([]string, error) func ReadFileByLine(path string)([]string, error)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -408,9 +414,8 @@ func main() {
} }
``` ```
### <span id="Zip">Zip</span> ### <span id="Zip">Zip</span>
<p>Create a zip file of fpath, fpath could be a file or a directory.</p> <p>Create a zip file of fpath, fpath could be a file or a directory.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -418,6 +423,7 @@ func main() {
```go ```go
func Zip(fpath string, destPath string) error func Zip(fpath string, destPath string) error
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -436,10 +442,8 @@ func main() {
} }
``` ```
### <span id="UnZip">UnZip</span> ### <span id="UnZip">UnZip</span>
<p>Unzip the file and save it to dest path.</p> <p>Unzip the file and save it to dest path.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -447,6 +451,7 @@ func main() {
```go ```go
func UnZip(zipFile string, destPath string) error func UnZip(zipFile string, destPath string) error
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -464,8 +469,3 @@ func main() {
} }
} }
``` ```

View File

@@ -1,15 +1,17 @@
# Fileutil # Fileutil
fileutil包支持文件基本操作。
fileutil 包支持文件基本操作。
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 源码: ## 源码:
- [https://github.com/duke-git/lancet/blob/main/fileutil/file.go](https://github.com/duke-git/lancet/blob/main/fileutil/file.go) - [https://github.com/duke-git/lancet/blob/main/fileutil/file.go](https://github.com/duke-git/lancet/blob/main/fileutil/file.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 用法: ## 用法:
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/fileutil" "github.com/duke-git/lancet/v2/fileutil"
@@ -19,29 +21,29 @@ import (
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 目录 ## 目录
- [ClearFile](#ClearFile)
- [CreateFile](#CreateFile) - [ClearFile](#ClearFile)
- [CreateDir](#CreateDir) - [CreateFile](#CreateFile)
- [CopyFile](#CopyFile) - [CreateDir](#CreateDir)
- [FileMode](#FileMode) - [CopyFile](#CopyFile)
- [MiMeType](#MiMeType) - [FileMode](#FileMode)
- [IsExist](#IsExist) - [MiMeType](#MiMeType)
- [IsLink](#IsLink) - [IsExist](#IsExist)
- [IsDir](#IsDir) - [IsLink](#IsLink)
- [ListFileNames](#ListFileNames) - [IsDir](#IsDir)
- [RemoveFile](#RemoveFile) - [ListFileNames](#ListFileNames)
- [ReadFileToString](#ReadFileToString) - [RemoveFile](#RemoveFile)
- [ReadFileByLine](#ReadFileByLine) - [ReadFileToString](#ReadFileToString)
- [Zip](#Zip) - [ReadFileByLine](#ReadFileByLine)
- [UnZip](#UnZip) - [Zip](#Zip)
- [UnZip](#UnZip)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 文档 ## 文档
### <span id="ClearFile">ClearFile</span> ### <span id="ClearFile">ClearFile</span>
<p>清空文件内容</p> <p>清空文件内容</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -49,6 +51,7 @@ import (
```go ```go
func ClearFile(path string) error func ClearFile(path string) error
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -68,6 +71,7 @@ func main() {
``` ```
### <span id="CreateFile">CreateFile</span> ### <span id="CreateFile">CreateFile</span>
<p>创建文件创建成功返回true, 否则返回false</p> <p>创建文件创建成功返回true, 否则返回false</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -75,6 +79,7 @@ func main() {
```go ```go
func CreateFile(path string) bool func CreateFile(path string) bool
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -91,8 +96,8 @@ func main() {
} }
``` ```
### <span id="CreateDir">CreateDir</span> ### <span id="CreateDir">CreateDir</span>
<p>使用绝对路径创建嵌套目录,例如/a/, /a/b/</p> <p>使用绝对路径创建嵌套目录,例如/a/, /a/b/</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -100,6 +105,7 @@ func main() {
```go ```go
func CreateDir(absPath string) error func CreateDir(absPath string) error
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -116,9 +122,8 @@ func main() {
} }
``` ```
### <span id="CopyFile">CopyFile</span> ### <span id="CopyFile">CopyFile</span>
<p>拷贝文件,会覆盖原有的文件</p> <p>拷贝文件,会覆盖原有的文件</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -126,6 +131,7 @@ func main() {
```go ```go
func CopyFile(srcFilePath string, dstFilePath string) error func CopyFile(srcFilePath string, dstFilePath string) error
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -144,9 +150,8 @@ func main() {
} }
``` ```
### <span id="FileMode">FileMode</span> ### <span id="FileMode">FileMode</span>
<p>获取文件mode信息</p> <p>获取文件mode信息</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -154,6 +159,7 @@ func main() {
```go ```go
func FileMode(path string) (fs.FileMode, error) func FileMode(path string) (fs.FileMode, error)
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -173,9 +179,8 @@ func main() {
} }
``` ```
### <span id="MiMeType">MiMeType</span> ### <span id="MiMeType">MiMeType</span>
<p>获取文件mime类型, 'file'参数的类型必须是string或者*os.File</p> <p>获取文件mime类型, 'file'参数的类型必须是string或者*os.File</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -183,6 +188,7 @@ func main() {
```go ```go
func MiMeType(file any) string func MiMeType(file any) string
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -204,10 +210,8 @@ func main() {
} }
``` ```
### <span id="IsExist">IsExist</span> ### <span id="IsExist">IsExist</span>
<p>判断文件或目录是否存在</p> <p>判断文件或目录是否存在</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -215,6 +219,7 @@ func main() {
```go ```go
func IsExist(path string) bool func IsExist(path string) bool
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -232,9 +237,8 @@ func main() {
} }
``` ```
### <span id="IsLink">IsLink</span> ### <span id="IsLink">IsLink</span>
<p>判断文件是否是符号链接</p> <p>判断文件是否是符号链接</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -242,6 +246,7 @@ func main() {
```go ```go
func IsLink(path string) bool func IsLink(path string) bool
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -258,16 +263,16 @@ func main() {
} }
``` ```
### <span id="IsDir">IsDir</span> ### <span id="IsDir">IsDir</span>
<p>判断参数是否是目录</p> <p>判断参数是否是目录</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func IsDir(path string) bool func IsDir(path string) bool
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -287,9 +292,8 @@ func main() {
} }
``` ```
### <span id="ListFileNames">ListFileNames</span> ### <span id="ListFileNames">ListFileNames</span>
<p>返回目录下所有文件名</p> <p>返回目录下所有文件名</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -297,6 +301,7 @@ func main() {
```go ```go
func ListFileNames(path string) ([]string, error) func ListFileNames(path string) ([]string, error)
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -313,9 +318,8 @@ func main() {
} }
``` ```
### <span id="RemoveFile">RemoveFile</span> ### <span id="RemoveFile">RemoveFile</span>
<p>删除文件</p> <p>删除文件</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -323,6 +327,7 @@ func main() {
```go ```go
func RemoveFile(path string) error func RemoveFile(path string) error
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -341,8 +346,8 @@ func main() {
} }
``` ```
### <span id="ReadFileToString">ReadFileToString</span> ### <span id="ReadFileToString">ReadFileToString</span>
<p>读取文件内容并返回字符串</p> <p>读取文件内容并返回字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -350,6 +355,7 @@ func main() {
```go ```go
func ReadFileToString(path string) (string, error) func ReadFileToString(path string) (string, error)
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -373,9 +379,8 @@ func main() {
} }
``` ```
### <span id="ReadFileByLine">ReadFileByLine</span> ### <span id="ReadFileByLine">ReadFileByLine</span>
<p>按行读取文件内容,返回字符串切片包含每一行</p> <p>按行读取文件内容,返回字符串切片包含每一行</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -383,6 +388,7 @@ func main() {
```go ```go
func ReadFileByLine(path string)([]string, error) func ReadFileByLine(path string)([]string, error)
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -407,9 +413,8 @@ func main() {
} }
``` ```
### <span id="Zip">Zip</span> ### <span id="Zip">Zip</span>
<p>zip压缩文件, fpath参数可以是文件或目录</p> <p>zip压缩文件, fpath参数可以是文件或目录</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -417,6 +422,7 @@ func main() {
```go ```go
func Zip(fpath string, destPath string) error func Zip(fpath string, destPath string) error
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -435,10 +441,8 @@ func main() {
} }
``` ```
### <span id="UnZip">UnZip</span> ### <span id="UnZip">UnZip</span>
<p>zip解压缩文件并保存在目录中</p> <p>zip解压缩文件并保存在目录中</p>
<b>Signature:</b> <b>Signature:</b>
@@ -446,6 +450,7 @@ func main() {
```go ```go
func UnZip(zipFile string, destPath string) error func UnZip(zipFile string, destPath string) error
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -463,8 +468,3 @@ func main() {
} }
} }
``` ```

View File

@@ -1,15 +1,17 @@
# Formatter # Formatter
formatter contains some functions for data formatting. formatter contains some functions for data formatting.
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Source: ## 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/formatter.go](https://github.com/duke-git/lancet/blob/main/formatter/formatter.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Usage: ## Usage:
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/formatter" "github.com/duke-git/lancet/v2/formatter"
@@ -19,15 +21,15 @@ import (
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Index ## Index
- [Comma](#Comma)
- [Comma](#Comma)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Documentation ## Documentation
### <span id="Comma">Comma</span> ### <span id="Comma">Comma</span>
<p>Add comma to a number value by every 3 numbers from right to left. ahead by symbol char. if value is a invalid number string like "aa", return empty string.</p> <p>Add comma to a number value by every 3 numbers from right to left. ahead by symbol char. if value is a invalid number string like "aa", return empty string.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -35,6 +37,7 @@ import (
```go ```go
func Comma[T constraints.Float | constraints.Integer | string](value T, symbol string) string func Comma[T constraints.Float | constraints.Integer | string](value T, symbol string) string
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -46,7 +49,17 @@ import (
) )
func main() { func main() {
fmt.Println(formatter.Comma("12345", "")) // "12,345" result1 := formatter.Comma("123", "")
fmt.Println(formatter.Comma(12345.67, "¥")) // "¥12,345.67" result2 := formatter.Comma("12345", "$")
result3 := formatter.Comma(1234567, "¥")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 123
// $12,345
// ¥1,234,567
} }
``` ```

View File

@@ -1,15 +1,17 @@
# Formatter # Formatter
formatter格式化器包含一些数据格式化处理方法。
formatter 格式化器包含一些数据格式化处理方法。
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 源码: ## 源码:
- [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/formatter.go](https://github.com/duke-git/lancet/blob/main/formatter/formatter.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 用法: ## 用法:
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/formatter" "github.com/duke-git/lancet/v2/formatter"
@@ -19,15 +21,15 @@ import (
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 目录 ## 目录
- [Comma](#Comma)
- [Comma](#Comma)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 文档 ## 文档
### <span id="Comma">Comma</span> ### <span id="Comma">Comma</span>
<p>用逗号每隔3位分割数字/字符串支持前缀添加符号。参数value必须是数字或者可以转为数字的字符串, 否则返回空字符串</p> <p>用逗号每隔3位分割数字/字符串支持前缀添加符号。参数value必须是数字或者可以转为数字的字符串, 否则返回空字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -35,6 +37,7 @@ import (
```go ```go
func Comma[T constraints.Float | constraints.Integer | string](value T, symbol string) string func Comma[T constraints.Float | constraints.Integer | string](value T, symbol string) string
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -46,7 +49,17 @@ import (
) )
func main() { func main() {
fmt.Println(formatter.Comma("12345", "")) // "12,345" result1 := formatter.Comma("123", "")
fmt.Println(formatter.Comma(12345.67, "¥")) // "¥12,345.67" result2 := formatter.Comma("12345", "$")
result3 := formatter.Comma(1234567, "¥")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 123
// $12,345
// ¥1,234,567
} }
``` ```

View File

@@ -1,16 +1,18 @@
# Function # Function
Package function can control the flow of function execution and support part of functional programming. Package function can control the flow of function execution and support part of functional programming.
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Source: ## Source:
- [https://github.com/duke-git/lancet/blob/main/function/function.go](https://github.com/duke-git/lancet/blob/main/function/function.go) - [https://github.com/duke-git/lancet/blob/main/function/function.go](https://github.com/duke-git/lancet/blob/main/function/function.go)
- [https://github.com/duke-git/lancet/blob/main/function/watcher.go](https://github.com/duke-git/lancet/blob/main/function/watcher.go) - [https://github.com/duke-git/lancet/blob/main/function/watcher.go](https://github.com/duke-git/lancet/blob/main/function/watcher.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Usage: ## Usage:
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/function" "github.com/duke-git/lancet/v2/function"
@@ -20,22 +22,22 @@ import (
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Index ## Index
- [After](#After)
- [Before](#Before) - [After](#After)
- [CurryFn](#CurryFn) - [Before](#Before)
- [Compose](#Compose) - [CurryFn](#CurryFn)
- [Debounced](#Debounced) - [Compose](#Compose)
- [Delay](#Delay) - [Debounced](#Debounced)
- [Pipeline](#Pipeline) - [Delay](#Delay)
- [Watcher](#Watcher) - [Pipeline](#Pipeline)
- [Watcher](#Watcher)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Documentation ## Documentation
### <span id="After">After</span> ### <span id="After">After</span>
<p>Creates a function that invokes given func once it's called n or more times.</p> <p>Creates a function that invokes given func once it's called n or more times.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -43,6 +45,7 @@ import (
```go ```go
func After(n int, fn any) func(args ...any) []reflect.Value func After(n int, fn any) func(args ...any) []reflect.Value
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -54,33 +57,18 @@ import (
) )
func main() { func main() {
arr := []string{"a", "b"} fn := function.After(2, func() {
f := function.After(len(arr), func(i int) int { fmt.Println("hello")
fmt.Println("last print") })
return i
})
type cb func(args ...any) []reflect.Value fn()
print := func(i int, s string, fn cb) { fn()
fmt.Printf("arr[%d] is %s \n", i, s)
fn(i)
}
fmt.Println("arr is", arr) // Output:
for i := 0; i < len(arr); i++ { // hello
print(i, arr[i], f)
}
//output:
// arr is [a b]
// arr[0] is a
// arr[1] is b
// last print
} }
``` ```
### <span id="Before">Before</span> ### <span id="Before">Before</span>
<p>creates a function that invokes func once it's called less than n times.</p> <p>creates a function that invokes func once it's called less than n times.</p>
@@ -90,6 +78,7 @@ func main() {
```go ```go
func Before(n int, fn any) func(args ...any) []reflect.Value func Before(n int, fn any) func(args ...any) []reflect.Value
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -102,29 +91,21 @@ import (
) )
func main() { func main() {
arr := []string{"a", "b", "c", "d", "e"} fn := function.Before(2, func() {
f := function.Before(3, func(i int) int { fmt.Println("hello")
return i })
})
var res []int64 fn()
type cb func(args ...any) []reflect.Value fn()
appendStr := func(i int, s string, fn cb) { fn()
v := fn(i) fn()
res = append(res, v[0].Int())
}
for i := 0; i < len(arr); i++ { // Output:
appendStr(i, arr[i], f) // hello
} // hello
expected := []int64{0, 1, 2, 2, 2}
fmt.Println(res) // 0, 1, 2, 2, 2
} }
``` ```
### <span id="CurryFn">CurryFn</span> ### <span id="CurryFn">CurryFn</span>
<p>Make curry function.</p> <p>Make curry function.</p>
@@ -135,6 +116,7 @@ func main() {
type CurryFn[T any] func(...T) T type CurryFn[T any] func(...T) T
func (cf CurryFn[T]) New(val T) func(...T) T func (cf CurryFn[T]) New(val T) func(...T) T
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -147,22 +129,23 @@ import (
func main() { func main() {
add := func(a, b int) int { add := func(a, b int) int {
return a + b return a + b
} }
var addCurry CurryFn[int] = func(values ...int) int { var addCurry function.CurryFn[int] = func(values ...int) int {
return add(values[0], values[1]) return add(values[0], values[1])
} }
add1 := addCurry.New(1) add1 := addCurry.New(1)
result := add1(2) result := add1(2)
fmt.Println(result) //3 fmt.Println(result)
// Output:
// 3
} }
``` ```
### <span id="Compose">Compose</span> ### <span id="Compose">Compose</span>
<p>Compose the function list from right to left, then return the composed function.</p> <p>Compose the function list from right to left, then return the composed function.</p>
@@ -172,6 +155,7 @@ func main() {
```go ```go
func Compose[T any](fnList ...func(...T) T) func(...T) T func Compose[T any](fnList ...func(...T) T) func(...T) T
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -183,22 +167,23 @@ import (
) )
func main() { func main() {
toUpper := func(strs ...string) string { toUpper := func(strs ...string) string {
return strings.ToUpper(strs[0]) return strings.ToUpper(strs[0])
} }
toLower := func(strs ...string) string { toLower := func(strs ...string) string {
return strings.ToLower(strs[0]) return strings.ToLower(strs[0])
} }
transform := Compose(toUpper, toLower) transform := function.Compose(toUpper, toLower)
result := transform("aBCde") result := transform("aBCde")
fmt.Println(result) //ABCDE fmt.Println(result)
// Output:
// ABCDE
} }
``` ```
### <span id="Debounced">Debounced</span> ### <span id="Debounced">Debounced</span>
<p>Creates a debounced function that delays invoking fn until after wait duration have elapsed since the last time the debounced function was invoked.</p> <p>Creates a debounced function that delays invoking fn until after wait duration have elapsed since the last time the debounced function was invoked.</p>
@@ -208,6 +193,7 @@ func main() {
```go ```go
func Debounced(fn func(), duration time.Duration) func() func Debounced(fn func(), duration time.Duration) func()
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -220,27 +206,34 @@ import (
func main() { func main() {
count := 0 count := 0
add := func() {
count++
}
debouncedAdd := function.Debounced(add, 50*time.Microsecond) add := func() {
function.debouncedAdd() count++
function.debouncedAdd() }
function.debouncedAdd()
function.debouncedAdd()
time.Sleep(100 * time.Millisecond) debouncedAdd := function.Debounced(add, 50*time.Microsecond)
fmt.Println(count) //1
function.debouncedAdd() debouncedAdd()
time.Sleep(100 * time.Millisecond) debouncedAdd()
fmt.Println(count) //2 debouncedAdd()
debouncedAdd()
time.Sleep(100 * time.Millisecond)
fmt.Println(count)
debouncedAdd()
time.Sleep(100 * time.Millisecond)
fmt.Println(count)
// Output:
// 1
// 2
} }
``` ```
### <span id="Delay">Delay</span> ### <span id="Delay">Delay</span>
<p>Invoke function after delayed time.</p> <p>Invoke function after delayed time.</p>
@@ -250,6 +243,7 @@ func main() {
```go ```go
func Delay(delay time.Duration, fn any, args ...any) func Delay(delay time.Duration, fn any, args ...any)
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -261,15 +255,17 @@ import (
) )
func main() { func main() {
var print = func(s string) { var print = func(s string) {
fmt.Println(count) //delay 2 seconds fmt.Println(s)
} }
function.Delay(2*time.Second, print, "delay 2 seconds")
function.Delay(2*time.Second, print, "hello")
// Output:
// hello
} }
``` ```
### <span id="Schedule">Schedule</span> ### <span id="Schedule">Schedule</span>
<p>Invoke function every duration time, until close the returned bool chan.</p> <p>Invoke function every duration time, until close the returned bool chan.</p>
@@ -279,6 +275,7 @@ func main() {
```go ```go
func Schedule(d time.Duration, fn any, args ...any) chan bool func Schedule(d time.Duration, fn any, args ...any) chan bool
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -290,20 +287,24 @@ import (
) )
func main() { func main() {
var res []string count := 0
appendStr := func(s string) {
res = append(res, s)
}
stop := function.Schedule(1*time.Second, appendStr, "*") increase := func() {
time.Sleep(5 * time.Second) count++
close(stop) }
fmt.Println(res) //[* * * * *] stop := function.Schedule(2*time.Second, increase)
time.Sleep(2 * time.Second)
close(stop)
fmt.Println(count)
// Output:
// 2
} }
``` ```
### <span id="Pipeline">Pipeline</span> ### <span id="Pipeline">Pipeline</span>
<p>Pipeline takes a list of functions and returns a function whose param will be passed into <p>Pipeline takes a list of functions and returns a function whose param will be passed into
@@ -314,6 +315,7 @@ the functions one by one.</p>
```go ```go
func Pipeline[T any](funcs ...func(T) T) func(T) T func Pipeline[T any](funcs ...func(T) T) func(T) T
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -326,22 +328,26 @@ import (
func main() { func main() {
addOne := func(x int) int { addOne := func(x int) int {
return x + 1 return x + 1
} }
double := func(x int) int { double := func(x int) int {
return 2 * x return 2 * x
} }
square := func(x int) int { square := func(x int) int {
return x * x return x * x
} }
fn := Pipeline(addOne, double, square) fn := function.Pipeline(addOne, double, square)
fmt.Println(fn(2)) //36 result := fn(2)
fmt.Println(result)
// Output:
// 36
} }
``` ```
### <span id="Watcher">Watcher</span> ### <span id="Watcher">Watcher</span>
<p>Watcher is used for record code excution time. can start/stop/reset the watch timer. get the elapsed time of function execution.</p> <p>Watcher is used for record code excution time. can start/stop/reset the watch timer. get the elapsed time of function execution.</p>
@@ -350,9 +356,9 @@ func main() {
```go ```go
type Watcher struct { type Watcher struct {
startTime int64 startTime int64
stopTime int64 stopTime int64
excuting bool excuting bool
} }
func NewWatcher() *Watcher func NewWatcher() *Watcher
func (w *Watcher) Start() //start the watcher func (w *Watcher) Start() //start the watcher
@@ -360,6 +366,7 @@ func (w *Watcher) Stop() //stop the watcher
func (w *Watcher) Reset() //reset the watcher func (w *Watcher) Reset() //reset the watcher
func (w *Watcher) GetElapsedTime() time.Duration //get the elapsed time of function execution func (w *Watcher) GetElapsedTime() time.Duration //get the elapsed time of function execution
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -371,31 +378,28 @@ import (
) )
func main() { func main() {
w := function.NewWatcher() w := function.NewWatcher()
w.Start() w.Start()
longRunningTask() longRunningTask()
fmt.Println(w.excuting) //true fmt.Println(w.excuting) //true
w.Stop() w.Stop()
eapsedTime := w.GetElapsedTime().Milliseconds() eapsedTime := w.GetElapsedTime().Milliseconds()
fmt.Println(eapsedTime)
w.Reset() fmt.Println(eapsedTime)
w.Reset()
} }
func longRunningTask() { func longRunningTask() {
var slice []int64 var slice []int64
for i := 0; i < 10000000; i++ { for i := 0; i < 10000000; i++ {
slice = append(slice, int64(i)) slice = append(slice, int64(i))
} }
} }
``` ```

View File

@@ -1,16 +1,18 @@
# Function # Function
function函数包控制函数执行流程包含部分函数式编程。
function 函数包控制函数执行流程,包含部分函数式编程。
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 源码: ## 源码:
- [https://github.com/duke-git/lancet/blob/main/function/function.go](https://github.com/duke-git/lancet/blob/main/function/function.go) - [https://github.com/duke-git/lancet/blob/main/function/function.go](https://github.com/duke-git/lancet/blob/main/function/function.go)
- [https://github.com/duke-git/lancet/blob/main/function/watcher.go](https://github.com/duke-git/lancet/blob/main/function/watcher.go) - [https://github.com/duke-git/lancet/blob/main/function/watcher.go](https://github.com/duke-git/lancet/blob/main/function/watcher.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 用法: ## 用法:
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/function" "github.com/duke-git/lancet/v2/function"
@@ -20,22 +22,22 @@ import (
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 目录 ## 目录
- [After](#After)
- [Before](#Before) - [After](#After)
- [CurryFn](#CurryFn) - [Before](#Before)
- [Compose](#Compose) - [CurryFn](#CurryFn)
- [Debounced](#Debounced) - [Compose](#Compose)
- [Delay](#Delay) - [Debounced](#Debounced)
- [Pipeline](#Pipeline) - [Delay](#Delay)
- [Watcher](#Watcher) - [Pipeline](#Pipeline)
- [Watcher](#Watcher)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 文档 ## 文档
### <span id="After">After</span> ### <span id="After">After</span>
<p>创建一个函数当他被调用n或更多次之后将马上触发fn</p> <p>创建一个函数当他被调用n或更多次之后将马上触发fn</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -43,6 +45,7 @@ import (
```go ```go
func After(n int, fn any) func(args ...any) []reflect.Value func After(n int, fn any) func(args ...any) []reflect.Value
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -54,33 +57,18 @@ import (
) )
func main() { func main() {
arr := []string{"a", "b"} fn := function.After(2, func() {
f := function.After(len(arr), func(i int) int { fmt.Println("hello")
fmt.Println("last print") })
return i
})
type cb func(args ...any) []reflect.Value fn()
print := func(i int, s string, fn cb) { fn()
fmt.Printf("arr[%d] is %s \n", i, s)
fn(i)
}
fmt.Println("arr is", arr) // Output:
for i := 0; i < len(arr); i++ { // hello
print(i, arr[i], f)
}
//output:
// arr is [a b]
// arr[0] is a
// arr[1] is b
// last print
} }
``` ```
### <span id="Before">Before</span> ### <span id="Before">Before</span>
<p>创建一个函数调用次数不超过n次之后再调用这个函数将返回一次最后调用fn的结果</p> <p>创建一个函数调用次数不超过n次之后再调用这个函数将返回一次最后调用fn的结果</p>
@@ -90,6 +78,7 @@ func main() {
```go ```go
func Before(n int, fn any) func(args ...any) []reflect.Value func Before(n int, fn any) func(args ...any) []reflect.Value
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -102,28 +91,21 @@ import (
) )
func main() { func main() {
arr := []string{"a", "b", "c", "d", "e"} fn := function.Before(2, func() {
f := function.Before(3, func(i int) int { fmt.Println("hello")
return i })
})
var res []int64 fn()
type cb func(args ...any) []reflect.Value fn()
appendStr := func(i int, s string, fn cb) { fn()
v := fn(i) fn()
res = append(res, v[0].Int())
}
for i := 0; i < len(arr); i++ { // Output:
appendStr(i, arr[i], f) // hello
} // hello
fmt.Println(res) // 0, 1, 2, 2, 2
} }
``` ```
### <span id="CurryFn">CurryFn</span> ### <span id="CurryFn">CurryFn</span>
<p>创建柯里化函数</p> <p>创建柯里化函数</p>
@@ -134,6 +116,7 @@ func main() {
type CurryFn[T any] func(...T) T type CurryFn[T any] func(...T) T
func (cf CurryFn[T]) New(val T) func(...T) T func (cf CurryFn[T]) New(val T) func(...T) T
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -145,23 +128,24 @@ import (
) )
func main() { func main() {
add := func(a, b int) int { add := func(a, b int) int {
return a + b return a + b
} }
var addCurry CurryFn[int] = func(values ...int) int { var addCurry function.CurryFn[int] = func(values ...int) int {
return add(values[0], values[1]) return add(values[0], values[1])
} }
add1 := addCurry.New(1) add1 := addCurry.New(1)
result := add1(2) result := add1(2)
fmt.Println(result) //3 fmt.Println(result)
// Output:
// 3
} }
``` ```
### <span id="Compose">Compose</span> ### <span id="Compose">Compose</span>
<p>从右至左组合函数列表fnList返回组合后的函数</p> <p>从右至左组合函数列表fnList返回组合后的函数</p>
@@ -171,6 +155,7 @@ func main() {
```go ```go
func Compose[T any](fnList ...func(...T) T) func(...T) T func Compose[T any](fnList ...func(...T) T) func(...T) T
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -182,22 +167,23 @@ import (
) )
func main() { func main() {
toUpper := func(strs ...string) string { toUpper := func(strs ...string) string {
return strings.ToUpper(strs[0]) return strings.ToUpper(strs[0])
} }
toLower := func(strs ...string) string { toLower := func(strs ...string) string {
return strings.ToLower(strs[0]) return strings.ToLower(strs[0])
} }
transform := Compose(toUpper, toLower) transform := function.Compose(toUpper, toLower)
result := transform("aBCde") result := transform("aBCde")
fmt.Println(result) //ABCDE fmt.Println(result)
// Output:
// ABCDE
} }
``` ```
### <span id="Debounced">Debounced</span> ### <span id="Debounced">Debounced</span>
<p>创建一个debounced函数该函数延迟调用fn直到自上次调用debounced函数后等待持续时间过去。</p> <p>创建一个debounced函数该函数延迟调用fn直到自上次调用debounced函数后等待持续时间过去。</p>
@@ -207,6 +193,7 @@ func main() {
```go ```go
func Debounced(fn func(), duration time.Duration) func() func Debounced(fn func(), duration time.Duration) func()
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -218,28 +205,35 @@ import (
) )
func main() { func main() {
count := 0 count := 0
add := func() {
count++ add := func() {
} count++
}
debouncedAdd := function.Debounced(add, 50*time.Microsecond) debouncedAdd := function.Debounced(add, 50*time.Microsecond)
function.debouncedAdd()
function.debouncedAdd()
function.debouncedAdd()
function.debouncedAdd()
time.Sleep(100 * time.Millisecond) debouncedAdd()
fmt.Println(count) //1 debouncedAdd()
debouncedAdd()
debouncedAdd()
function.debouncedAdd() time.Sleep(100 * time.Millisecond)
time.Sleep(100 * time.Millisecond)
fmt.Println(count) //2 fmt.Println(count)
debouncedAdd()
time.Sleep(100 * time.Millisecond)
fmt.Println(count)
// Output:
// 1
// 2
} }
``` ```
### <span id="Delay">Delay</span> ### <span id="Delay">Delay</span>
<p>延迟delay时间后调用函数</p> <p>延迟delay时间后调用函数</p>
@@ -249,6 +243,7 @@ func main() {
```go ```go
func Delay(delay time.Duration, fn any, args ...any) func Delay(delay time.Duration, fn any, args ...any)
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -260,15 +255,17 @@ import (
) )
func main() { func main() {
var print = func(s string) { var print = func(s string) {
fmt.Println(count) //test delay fmt.Println(s)
} }
function.Delay(2*time.Second, print, "test delay")
function.Delay(2*time.Second, print, "hello")
// Output:
// hello
} }
``` ```
### <span id="Schedule">Schedule</span> ### <span id="Schedule">Schedule</span>
<p>每次持续时间调用函数,直到关闭返回的 bool chan</p> <p>每次持续时间调用函数,直到关闭返回的 bool chan</p>
@@ -278,6 +275,7 @@ func main() {
```go ```go
func Schedule(d time.Duration, fn any, args ...any) chan bool func Schedule(d time.Duration, fn any, args ...any) chan bool
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -289,21 +287,24 @@ import (
) )
func main() { func main() {
var res []string count := 0
appendStr := func(s string) {
res = append(res, s)
}
stop := function.Schedule(1*time.Second, appendStr, "*") increase := func() {
time.Sleep(5 * time.Second) count++
close(stop) }
fmt.Println(res) //[* * * * *] stop := function.Schedule(2*time.Second, increase)
time.Sleep(2 * time.Second)
close(stop)
fmt.Println(count)
// Output:
// 2
} }
``` ```
### <span id="Pipeline">Pipeline</span> ### <span id="Pipeline">Pipeline</span>
<p>执行函数pipeline.</p> <p>执行函数pipeline.</p>
@@ -313,6 +314,7 @@ func main() {
```go ```go
func Pipeline[T any](funcs ...func(T) T) func(T) T func Pipeline[T any](funcs ...func(T) T) func(T) T
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -325,23 +327,26 @@ import (
func main() { func main() {
addOne := func(x int) int { addOne := func(x int) int {
return x + 1 return x + 1
} }
double := func(x int) int { double := func(x int) int {
return 2 * x return 2 * x
} }
square := func(x int) int { square := func(x int) int {
return x * x return x * x
} }
f := Pipeline(addOne, double, square) fn := function.Pipeline(addOne, double, square)
fmt.Println(fn(2)) //36 result := fn(2)
fmt.Println(result)
// Output:
// 36
} }
``` ```
### <span id="Watcher">Watcher</span> ### <span id="Watcher">Watcher</span>
<p>Watcher用于记录代码执行时间。可以启动/停止/重置手表定时器。获取函数执行的时间。</p> <p>Watcher用于记录代码执行时间。可以启动/停止/重置手表定时器。获取函数执行的时间。</p>
@@ -350,9 +355,9 @@ func main() {
```go ```go
type Watcher struct { type Watcher struct {
startTime int64 startTime int64
stopTime int64 stopTime int64
excuting bool excuting bool
} }
func NewWatcher() *Watcher func NewWatcher() *Watcher
func (w *Watcher) Start() //start the watcher func (w *Watcher) Start() //start the watcher
@@ -360,6 +365,7 @@ func (w *Watcher) Stop() //stop the watcher
func (w *Watcher) Reset() //reset the watcher func (w *Watcher) Reset() //reset the watcher
func (w *Watcher) GetElapsedTime() time.Duration //get the elapsed time of function execution func (w *Watcher) GetElapsedTime() time.Duration //get the elapsed time of function execution
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -373,30 +379,27 @@ import (
func main() { func main() {
w := function.NewWatcher() w := function.NewWatcher()
w.Start() w.Start()
longRunningTask() longRunningTask()
fmt.Println(w.excuting) //true fmt.Println(w.excuting) //true
w.Stop() w.Stop()
eapsedTime := w.GetElapsedTime().Milliseconds() eapsedTime := w.GetElapsedTime().Milliseconds()
fmt.Println(eapsedTime)
w.Reset() fmt.Println(eapsedTime)
w.Reset()
} }
func longRunningTask() { func longRunningTask() {
var slice []int64 var slice []int64
for i := 0; i < 10000000; i++ { for i := 0; i < 10000000; i++ {
slice = append(slice, int64(i)) slice = append(slice, int64(i))
} }
} }
``` ```

View File

@@ -1,16 +1,17 @@
# Maputil # Maputil
Package maputil includes some functions to manipulate map. Package maputil includes some functions to manipulate map.
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Source: ## Source:
- [https://github.com/duke-git/lancet/blob/main/maputil/map.go](https://github.com/duke-git/lancet/blob/main/maputil/map.go) - [https://github.com/duke-git/lancet/blob/main/maputil/map.go](https://github.com/duke-git/lancet/blob/main/maputil/map.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Example: ## Example:
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/maputil" "github.com/duke-git/lancet/v2/maputil"
@@ -20,22 +21,22 @@ import (
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Index ## Index
- [ForEach](#ForEach)
- [Filter](#Filter) - [ForEach](#ForEach)
- [Intersect](#Intersect) - [Filter](#Filter)
- [Keys](#Keys) - [Intersect](#Intersect)
- [Merge](#Merge) - [Keys](#Keys)
- [Minus](#Minus) - [Merge](#Merge)
- [Values](#Values) - [Minus](#Minus)
- [IsDisjoint](#IsDisjoint) - [Values](#Values)
- [IsDisjoint](#IsDisjoint)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Documentation ## Documentation
### <span id="ForEach">ForEach</span> ### <span id="ForEach">ForEach</span>
<p>Executes iteratee funcation for every key and value pair in map.</p> <p>Executes iteratee funcation for every key and value pair in map.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -43,6 +44,7 @@ import (
```go ```go
func ForEach[K comparable, V any](m map[K]V, iteratee func(key K, value V)) func ForEach[K comparable, V any](m map[K]V, iteratee func(key K, value V))
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -54,26 +56,28 @@ import (
) )
func main() { func main() {
m := map[string]int{ m := map[string]int{
"a": 1, "a": 1,
"b": 2, "b": 2,
"c": 3, "c": 3,
"d": 4, "d": 4,
} }
var sum int var sum int
maputil.ForEach(m, func(_ string, value int) { maputil.ForEach(m, func(_ string, value int) {
sum += value sum += value
}) })
fmt.Println(sum) // 10
fmt.Println(sum)
// Output:
// 10
} }
``` ```
### <span id="Filter">Filter</span> ### <span id="Filter">Filter</span>
<p>Iterates over map, return a new map contains all key and value pairs pass the predicate function.</p> <p>Iterates over map, return a new map contains all key and value pairs pass the predicate function.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -81,6 +85,7 @@ func main() {
```go ```go
func Filter[K comparable, V any](m map[K]V, predicate func(key K, value V) bool) map[K]V func Filter[K comparable, V any](m map[K]V, predicate func(key K, value V) bool) map[K]V
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -92,29 +97,32 @@ import (
) )
func main() { func main() {
m := map[string]int{ m := map[string]int{
"a": 1, "a": 1,
"b": 2, "b": 2,
"c": 3, "c": 3,
"d": 4, "d": 4,
"e": 5, "e": 5,
} }
isEven := func(_ string, value int) bool { isEven := func(_ string, value int) bool {
return value%2 == 0 return value%2 == 0
} }
maputil.Filter(m, func(_ string, value int) { maputil.Filter(m, func(_ string, value int) {
sum += value sum += value
}) })
res := maputil.Filter(m, isEven)
fmt.Println(res) // map[string]int{"b": 2, "d": 4,} result := maputil.Filter(m, isEven)
fmt.Println(result)
// Output:
// map[b:2 d:4]
} }
``` ```
### <span id="Intersect">Intersect</span> ### <span id="Intersect">Intersect</span>
<p>Iterates over maps, return a new map of key and value pairs in all given maps.</p> <p>Iterates over maps, return a new map of key and value pairs in all given maps.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -122,6 +130,7 @@ func main() {
```go ```go
func Intersect[K comparable, V any](maps ...map[K]V) map[K]V func Intersect[K comparable, V any](maps ...map[K]V) map[K]V
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -133,37 +142,42 @@ import (
) )
func main() { func main() {
m1 := map[string]int{ m1 := map[string]int{
"a": 1, "a": 1,
"b": 2, "b": 2,
"c": 3, "c": 3,
} }
m2 := map[string]int{ m2 := map[string]int{
"a": 1, "a": 1,
"b": 2, "b": 2,
"c": 6, "c": 6,
"d": 7, "d": 7,
} }
m3 := map[string]int{ m3 := map[string]int{
"a": 1, "a": 1,
"b": 9, "b": 9,
"e": 9, "e": 9,
} }
fmt.Println(maputil.Intersect(m1)) // map[string]int{"a": 1, "b": 2, "c": 3} result1 := maputil.Intersect(m1)
result2 := maputil.Intersect(m1, m2)
result3 := maputil.Intersect(m1, m2, m3)
fmt.Println(maputil.Intersect(m1, m2)) // map[string]int{"a": 1, "b": 2} fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(maputil.Intersect(m1, m2, m3)) // map[string]int{"a": 1} // Output:
// map[a:1 b:2 c:3]
// map[a:1 b:2]
// map[a:1]
} }
``` ```
### <span id="Keys">Keys</span> ### <span id="Keys">Keys</span>
<p>Returns a slice of the map's keys.</p> <p>Returns a slice of the map's keys.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -171,6 +185,7 @@ func main() {
```go ```go
func Keys[K comparable, V any](m map[K]V) []K func Keys[K comparable, V any](m map[K]V) []K
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -182,24 +197,26 @@ import (
) )
func main() { func main() {
m := map[int]string{ m := map[int]string{
1: "a", 1: "a",
2: "a", 2: "a",
3: "b", 3: "b",
4: "c", 4: "c",
5: "d", 5: "d",
} }
keys := maputil.Keys(m) keys := maputil.Keys(m)
sort.Ints(keys) sort.Ints(keys)
fmt.Println(keys) // []int{1, 2, 3, 4, 5}
fmt.Println(keys)
// Output:
// [1 2 3 4 5]
} }
``` ```
### <span id="Merge">Merge</span> ### <span id="Merge">Merge</span>
<p>Merge maps, next key will overwrite previous key.</p> <p>Merge maps, next key will overwrite previous key.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -207,6 +224,7 @@ func main() {
```go ```go
func Merge[K comparable, V any](maps ...map[K]V) map[K]V func Merge[K comparable, V any](maps ...map[K]V) map[K]V
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -218,22 +236,26 @@ import (
) )
func main() { func main() {
m1 := map[int]string{ m1 := map[int]string{
1: "a", 1: "a",
2: "b", 2: "b",
} }
m2 := map[int]string{ m2 := map[int]string{
1: "1", 1: "1",
3: "2", 3: "2",
} }
fmt.Println(maputil.Merge(m1, m2)) // map[int]string{1:"1", 2:"b", 3:"2",}
result := maputil.Merge(m1, m2)
fmt.Println(result)
// Output:
// map[1:c 2:b 3:d]
} }
``` ```
### <span id="Minus">Minus</span> ### <span id="Minus">Minus</span>
<p>Creates an map of whose key in mapA but not in mapB.</p> <p>Creates an map of whose key in mapA but not in mapB.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -241,6 +263,7 @@ func main() {
```go ```go
func Minus[K comparable, V any](mapA, mapB map[K]V) map[K]V func Minus[K comparable, V any](mapA, mapB map[K]V) map[K]V
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -252,25 +275,29 @@ import (
) )
func main() { func main() {
m1 := map[string]int{ m1 := map[string]int{
"a": 1, "a": 1,
"b": 2, "b": 2,
"c": 3, "c": 3,
} }
m2 := map[string]int{ m2 := map[string]int{
"a": 11, "a": 11,
"b": 22, "b": 22,
"d": 33, "d": 33,
} }
result := maputil.Minus(m1, m2)
fmt.Println(maputil.Minus(m1, m2)) //map[string]int{"c": 3} fmt.Println(result)
// Output:
// map[c:3]
} }
``` ```
### <span id="Values">Values</span> ### <span id="Values">Values</span>
<p>Returns a slice of the map's values.</p> <p>Returns a slice of the map's values.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -278,6 +305,7 @@ func main() {
```go ```go
func Values[K comparable, V any](m map[K]V) []V func Values[K comparable, V any](m map[K]V) []V
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -289,22 +317,26 @@ import (
) )
func main() { func main() {
m := map[int]string{ m := map[int]string{
1: "a", 1: "a",
2: "a", 2: "a",
3: "b", 3: "b",
4: "c", 4: "c",
5: "d", 5: "d",
} }
values := maputil.Values(m) values := maputil.Values(m)
sort.Strings(values) sort.Strings(values)
fmt.Println(values) // []string{"a", "a", "b", "c", "d"} fmt.Println(values)
// Output:
// [a a b c d]
} }
``` ```
### <span id="IsDisjoint">IsDisjoint</span> ### <span id="IsDisjoint">IsDisjoint</span>
<p>Checks two maps are disjoint if they have no keys in common</p> <p>Checks two maps are disjoint if they have no keys in common</p>
<b>Signature:</b> <b>Signature:</b>
@@ -312,6 +344,7 @@ func main() {
```go ```go
func IsDisjoint[K comparable, V any](mapA, mapB map[K]V) bool func IsDisjoint[K comparable, V any](mapA, mapB map[K]V) bool
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -323,30 +356,28 @@ import (
) )
func main() { func main() {
m1 := map[int]string{ m1 := map[string]int{
1: "a", "a": 1,
2: "a", "b": 2,
3: "b", "c": 3,
4: "c", }
5: "d",
}
m2 := map[int]string{ m2 := map[string]int{
1: "a", "d": 22,
2: "a", }
3: "b",
4: "c",
5: "d",
}
m3 := map[int]string{ m3 := map[string]int{
6: "a", "a": 22,
} }
ok := maputil.IsDisjoint(m2, m1) result1 := maputil.IsDisjoint(m1, m2)
fmt.Println(ok) // false result2 := maputil.IsDisjoint(m1, m3)
ok = maputil.IsDisjoint(m2, m3) fmt.Println(result1)
fmt.Println(ok) // true fmt.Println(result2)
// Output:
// true
// false
} }
``` ```

View File

@@ -1,16 +1,17 @@
# Maputil # Maputil
maputil包包括一些操作map的函数。
maputil 包包括一些操作 map 的函数。
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 源码: ## 源码:
- [https://github.com/duke-git/lancet/blob/main/maputil/map.go](https://github.com/duke-git/lancet/blob/main/maputil/map.go) - [https://github.com/duke-git/lancet/blob/main/maputil/map.go](https://github.com/duke-git/lancet/blob/main/maputil/map.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 用法: ## 用法:
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/maputil" "github.com/duke-git/lancet/v2/maputil"
@@ -20,22 +21,22 @@ import (
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 目录: ## 目录:
- [ForEach](#ForEach)
- [Filter](#Filter) - [ForEach](#ForEach)
- [Intersect](#Intersect) - [Filter](#Filter)
- [Keys](#Keys) - [Intersect](#Intersect)
- [Merge](#Merge) - [Keys](#Keys)
- [Minus](#Minus) - [Merge](#Merge)
- [Values](#Values) - [Minus](#Minus)
- [IsDisjoint](#IsDisjoint) - [Values](#Values)
- [IsDisjoint](#IsDisjoint)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## API文档: ## API 文档:
### <span id="ForEach">ForEach</span> ### <span id="ForEach">ForEach</span>
<p>对map中的每对key和value执行iteratee函数</p> <p>对map中的每对key和value执行iteratee函数</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -43,6 +44,7 @@ import (
```go ```go
func ForEach[K comparable, V any](m map[K]V, iteratee func(key K, value V)) func ForEach[K comparable, V any](m map[K]V, iteratee func(key K, value V))
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -54,26 +56,28 @@ import (
) )
func main() { func main() {
m := map[string]int{ m := map[string]int{
"a": 1, "a": 1,
"b": 2, "b": 2,
"c": 3, "c": 3,
"d": 4, "d": 4,
} }
var sum int var sum int
maputil.ForEach(m, func(_ string, value int) { maputil.ForEach(m, func(_ string, value int) {
sum += value sum += value
}) })
fmt.Println(sum) // 10
fmt.Println(sum)
// Output:
// 10
} }
``` ```
### <span id="Filter">Filter</span> ### <span id="Filter">Filter</span>
<p>迭代map中的每对key和value, 返回符合predicate函数的key, value</p> <p>迭代map中的每对key和value, 返回符合predicate函数的key, value</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -81,6 +85,7 @@ func main() {
```go ```go
func Filter[K comparable, V any](m map[K]V, predicate func(key K, value V) bool) map[K]V func Filter[K comparable, V any](m map[K]V, predicate func(key K, value V) bool) map[K]V
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -92,29 +97,32 @@ import (
) )
func main() { func main() {
m := map[string]int{ m := map[string]int{
"a": 1, "a": 1,
"b": 2, "b": 2,
"c": 3, "c": 3,
"d": 4, "d": 4,
"e": 5, "e": 5,
} }
isEven := func(_ string, value int) bool { isEven := func(_ string, value int) bool {
return value%2 == 0 return value%2 == 0
} }
maputil.Filter(m, func(_ string, value int) { maputil.Filter(m, func(_ string, value int) {
sum += value sum += value
}) })
res := maputil.Filter(m, isEven)
fmt.Println(res) // map[string]int{"b": 2, "d": 4,} result := Filter(m, isEven)
fmt.Println(result)
// Output:
// map[b:2 d:4]
} }
``` ```
### <span id="Intersect">Intersect</span> ### <span id="Intersect">Intersect</span>
<p>多个map的交集操作</p> <p>多个map的交集操作</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -122,6 +130,7 @@ func main() {
```go ```go
func Intersect[K comparable, V any](maps ...map[K]V) map[K]V func Intersect[K comparable, V any](maps ...map[K]V) map[K]V
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -133,37 +142,42 @@ import (
) )
func main() { func main() {
m1 := map[string]int{ m1 := map[string]int{
"a": 1, "a": 1,
"b": 2, "b": 2,
"c": 3, "c": 3,
} }
m2 := map[string]int{ m2 := map[string]int{
"a": 1, "a": 1,
"b": 2, "b": 2,
"c": 6, "c": 6,
"d": 7, "d": 7,
} }
m3 := map[string]int{ m3 := map[string]int{
"a": 1, "a": 1,
"b": 9, "b": 9,
"e": 9, "e": 9,
} }
fmt.Println(maputil.Intersect(m1)) // map[string]int{"a": 1, "b": 2, "c": 3} result1 := maputil.Intersect(m1)
result2 := maputil.Intersect(m1, m2)
result3 := maputil.Intersect(m1, m2, m3)
fmt.Println(maputil.Intersect(m1, m2)) // map[string]int{"a": 1, "b": 2} fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(maputil.Intersect(m1, m2, m3)) // map[string]int{"a": 1} // Output:
// map[a:1 b:2 c:3]
// map[a:1 b:2]
// map[a:1]
} }
``` ```
### <span id="Keys">Keys</span> ### <span id="Keys">Keys</span>
<p>返回map中所有key的切片</p> <p>返回map中所有key的切片</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -171,6 +185,7 @@ func main() {
```go ```go
func Keys[K comparable, V any](m map[K]V) []K func Keys[K comparable, V any](m map[K]V) []K
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -182,24 +197,26 @@ import (
) )
func main() { func main() {
m := map[int]string{ m := map[int]string{
1: "a", 1: "a",
2: "a", 2: "a",
3: "b", 3: "b",
4: "c", 4: "c",
5: "d", 5: "d",
} }
keys := maputil.Keys(m) keys := maputil.Keys(m)
sort.Ints(keys) sort.Ints(keys)
fmt.Println(keys) // []int{1, 2, 3, 4, 5}
fmt.Println(keys)
// Output:
// [1 2 3 4 5]
} }
``` ```
### <span id="Merge">Merge</span> ### <span id="Merge">Merge</span>
<p>合并多个maps, 相同的key会被后来的key覆盖</p> <p>合并多个maps, 相同的key会被后来的key覆盖</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -207,6 +224,7 @@ func main() {
```go ```go
func Merge[K comparable, V any](maps ...map[K]V) map[K]V func Merge[K comparable, V any](maps ...map[K]V) map[K]V
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -218,21 +236,26 @@ import (
) )
func main() { func main() {
m1 := map[int]string{ m1 := map[int]string{
1: "a", 1: "a",
2: "b", 2: "b",
} }
m2 := map[int]string{ m2 := map[int]string{
1: "1", 1: "1",
3: "2", 3: "2",
} }
fmt.Println(maputil.Merge(m1, m2)) // map[int]string{1:"1", 2:"b", 3:"2",}
result := maputil.Merge(m1, m2)
fmt.Println(result)
// Output:
// map[1:c 2:b 3:d]
} }
``` ```
### <span id="Minus">Minus</span> ### <span id="Minus">Minus</span>
<p>返回一个map其中的key存在于mapA不存在于mapB.</p> <p>返回一个map其中的key存在于mapA不存在于mapB.</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -240,6 +263,7 @@ func main() {
```go ```go
func Minus[K comparable, V any](mapA, mapB map[K]V) map[K]V func Minus[K comparable, V any](mapA, mapB map[K]V) map[K]V
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -251,25 +275,29 @@ import (
) )
func main() { func main() {
m1 := map[string]int{ m1 := map[string]int{
"a": 1, "a": 1,
"b": 2, "b": 2,
"c": 3, "c": 3,
} }
m2 := map[string]int{ m2 := map[string]int{
"a": 11, "a": 11,
"b": 22, "b": 22,
"d": 33, "d": 33,
} }
fmt.Println(maputil.Minus(m1, m2)) //map[string]int{"c": 3} result := maputil.Minus(m1, m2)
fmt.Println(result)
// Output:
// map[c:3]
} }
``` ```
### <span id="Values">Values</span> ### <span id="Values">Values</span>
<p>返回map中所有value的切片</p> <p>返回map中所有value的切片</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -277,6 +305,7 @@ func main() {
```go ```go
func Values[K comparable, V any](m map[K]V) []V func Values[K comparable, V any](m map[K]V) []V
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -288,23 +317,24 @@ import (
) )
func main() { func main() {
m := map[int]string{ m := map[int]string{
1: "a", 1: "a",
2: "a", 2: "a",
3: "b", 3: "b",
4: "c", 4: "c",
5: "d", 5: "d",
} }
values := maputil.Values(m) values := maputil.Values(m)
sort.Strings(values) sort.Strings(values)
fmt.Println(values) // []string{"a", "a", "b", "c", "d"} // Output:
// [a a b c d]
} }
``` ```
### <span id="IsDisjoint">IsDisjoint</span> ### <span id="IsDisjoint">IsDisjoint</span>
<p>验证两个map是否具有不同的key</p> <p>验证两个map是否具有不同的key</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -312,6 +342,7 @@ func main() {
```go ```go
func IsDisjoint[K comparable, V any](mapA, mapB map[K]V) bool func IsDisjoint[K comparable, V any](mapA, mapB map[K]V) bool
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -323,30 +354,28 @@ import (
) )
func main() { func main() {
m1 := map[int]string{ m1 := map[string]int{
1: "a", "a": 1,
2: "a", "b": 2,
3: "b", "c": 3,
4: "c", }
5: "d",
}
m2 := map[int]string{ m2 := map[string]int{
1: "a", "d": 22,
2: "a", }
3: "b",
4: "c",
5: "d",
}
m3 := map[int]string{ m3 := map[string]int{
6: "a", "a": 22,
} }
ok := maputil.IsDisjoint(m2, m1) result1 := maputil.IsDisjoint(m1, m2)
fmt.Println(ok) // false result2 := maputil.IsDisjoint(m1, m3)
ok = maputil.IsDisjoint(m2, m3) fmt.Println(result1)
fmt.Println(ok) // true fmt.Println(result2)
// Output:
// true
// false
} }
``` ```

View File

@@ -1,16 +1,17 @@
# Mathutil # Mathutil
Package mathutil implements some functions for math calculation. Package mathutil implements some functions for math calculation.
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Source: ## Source:
- [https://github.com/duke-git/lancet/blob/main/mathutil/mathutil.go](https://github.com/duke-git/lancet/blob/main/mathutil/mathutil.go) - [https://github.com/duke-git/lancet/blob/main/mathutil/mathutil.go](https://github.com/duke-git/lancet/blob/main/mathutil/mathutil.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Example: ## Example:
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/mathutil" "github.com/duke-git/lancet/v2/mathutil"
@@ -20,26 +21,26 @@ import (
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Index ## Index
- [Average](#Average)
- [Exponent](#Exponent) - [Average](#Average)
- [Fibonacci](#Fibonacci) - [Exponent](#Exponent)
- [Factorial](#Factorial) - [Fibonacci](#Fibonacci)
- [Max](#Max) - [Factorial](#Factorial)
- [MaxBy](#MaxBy) - [Max](#Max)
- [Min](#Min) - [MaxBy](#MaxBy)
- [MinBy](#MaxBy) - [Min](#Min)
- [Percent](#Percent) - [MinBy](#MaxBy)
- [RoundToFloat](#RoundToFloat) - [Percent](#Percent)
- [RoundToString](#RoundToString) - [RoundToFloat](#RoundToFloat)
- [TruncRound](#TruncRound) - [RoundToString](#RoundToString)
- [TruncRound](#TruncRound)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Documentation ## Documentation
### <span id="Average">Average</span> ### <span id="Average">Average</span>
<p>Return average value of numbers. Maybe call RoundToFloat to round result.</p> <p>Return average value of numbers. Maybe call RoundToFloat to round result.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -47,6 +48,7 @@ import (
```go ```go
func Average[T constraints.Integer | constraints.Float](numbers ...T) T func Average[T constraints.Integer | constraints.Float](numbers ...T) T
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -58,16 +60,22 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Average(0, 0)) //0 result1 := mathutil.Average(1, 2)
fmt.Println(mathutil.Average(1, 1)) //1
avg := mathutil.Average(1.2, 1.4) //1.2999999998 avg := mathutil.Average(1.2, 1.4)
roundAvg := mmathutil.RoundToFloat(avg, 1) // 1.3 result2 := mathutil.RoundToFloat(avg, 1)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 1
// 1.3
} }
``` ```
### <span id="Exponent">Exponent</span> ### <span id="Exponent">Exponent</span>
<p>Calculate x to the nth power.</p> <p>Calculate x to the nth power.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -75,6 +83,7 @@ func main() {
```go ```go
func Exponent(x, n int64) int64 func Exponent(x, n int64) int64
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -86,15 +95,23 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Exponent(10, 0)) //1 result1 := mathutil.Exponent(10, 0)
fmt.Println(mathutil.Exponent(10, 1)) //10 result2 := mathutil.Exponent(10, 1)
fmt.Println(mathutil.Exponent(10, 2)) //100 result3 := mathutil.Exponent(10, 2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 1
// 10
// 100
} }
``` ```
### <span id="Fibonacci">Fibonacci</span> ### <span id="Fibonacci">Fibonacci</span>
<p>Calculate the nth number of fibonacci sequence.</p> <p>Calculate the nth number of fibonacci sequence.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -102,6 +119,7 @@ func main() {
```go ```go
func Fibonacci(first, second, n int) int func Fibonacci(first, second, n int) int
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -113,17 +131,23 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Fibonacci(1, 1, 1)) //1 result1 := mathutil.Fibonacci(1, 1, 1)
fmt.Println(mathutil.Fibonacci(1, 1, 2)) //1 result2 := mathutil.Fibonacci(1, 1, 2)
fmt.Println(mathutil.Fibonacci(1, 1, 3)) //2 result3 := mathutil.Fibonacci(1, 1, 5)
fmt.Println(mathutil.Fibonacci(1, 1, 4)) //3
fmt.Println(mathutil.Fibonacci(1, 1, 5)) //5 fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 1
// 1
// 5
} }
``` ```
### <span id="Factorial">Factorial</span> ### <span id="Factorial">Factorial</span>
<p>Calculate the factorial of x.</p> <p>Calculate the factorial of x.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -131,6 +155,7 @@ func main() {
```go ```go
func Factorial(x uint) uint func Factorial(x uint) uint
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -142,16 +167,23 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Factorial(0)) //1 result1 := mathutil.Factorial(1)
fmt.Println(mathutil.Factorial(1)) //1 result2 := mathutil.Factorial(2)
fmt.Println(mathutil.Factorial(2)) //2 result3 := mathutil.Factorial(3)
fmt.Println(mathutil.Factorial(3)) //6
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 1
// 2
// 6
} }
``` ```
### <span id="Max">Max</span> ### <span id="Max">Max</span>
<p>Return max value of numbers.</p> <p>Return max value of numbers.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -159,6 +191,7 @@ func main() {
```go ```go
func Max[T constraints.Integer | constraints.Float](numbers ...T) T func Max[T constraints.Integer | constraints.Float](numbers ...T) T
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -170,23 +203,28 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Max(0, 0)) //0 result1 := mathutil.Max(1, 2, 3)
fmt.Println(mathutil.Max(1, 2, 3)) //3 result2 := mathutil.Max(1.2, 1.4, 1.1, 1.4)
fmt.Println(mathutil.Max(1.2, 1.4, 1.1, 1.4)) //1.4
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 3
// 1.4
} }
``` ```
### <span id="MaxBy">MaxBy</span> ### <span id="MaxBy">MaxBy</span>
<p>Return the maximum value of a slice using the given comparator function.</p> <p>Return the maximum value of a slice using the given comparator function.</p>
<b>Signature:</b> <b>Signature:</b>
```go ```go
func MaxBy[T any](slice []T, comparator func(T, T) bool) T func MaxBy[T any](slice []T, comparator func(T, T) bool) T
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -198,26 +236,31 @@ import (
) )
func main() { func main() {
res1 := mathutil.MaxBy([]string{"a", "ab", "abc"}, func(v1, v2 string) bool { result1 := mathutil.MaxBy([]string{"a", "ab", "abc"}, func(v1, v2 string) bool {
return len(v1) > len(v2) return len(v1) > len(v2)
}) })
fmt.Println(res1) //abc
res2 := mathutil.MaxBy([]string{"abd", "abc", "ab"}, func(v1, v2 string) bool { result2 := mathutil.MaxBy([]string{"abd", "abc", "ab"}, func(v1, v2 string) bool {
return len(v1) > len(v2) return len(v1) > len(v2)
}) })
fmt.Println(res2) //abd
res3 := mathutil.MaxBy([]string{}, func(v1, v2 string) bool { result3 := mathutil.MaxBy([]string{}, func(v1, v2 string) bool {
return len(v1) > len(v2) return len(v1) > len(v2)
}) })
fmt.Println(res3) //“”
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// abc
// abd
//
} }
``` ```
### <span id="Min">Min</span> ### <span id="Min">Min</span>
<p>Return the minimum value of numbers.</p> <p>Return the minimum value of numbers.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -225,6 +268,7 @@ func main() {
```go ```go
func Min[T constraints.Integer | constraints.Float](numbers ...T) T func Min[T constraints.Integer | constraints.Float](numbers ...T) T
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -236,22 +280,28 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Min(0, 0)) //0 result1 := mathutil.Min(1, 2, 3)
fmt.Println(mathutil.Min(1, 2, 3)) //1 result2 := mathutil.Min(1.2, 1.4, 1.1, 1.4)
fmt.Println(mathutil.Min(1.2, 1.4, 1.1, 1.4)) //1.1
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 1
// 1.1
} }
``` ```
### <span id="MinBy">MinBy</span> ### <span id="MinBy">MinBy</span>
<p>Return the minimum value of a slice using the given comparator function.</p> <p>Return the minimum value of a slice using the given comparator function.</p>
<b>Signature:</b> <b>Signature:</b>
```go ```go
func MinBy[T any](slice []T, comparator func(T, T) bool) T func MinBy[T any](slice []T, comparator func(T, T) bool) T
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -263,27 +313,31 @@ import (
) )
func main() { func main() {
res1 := mathutil.MinBy([]string{"a", "ab", "abc"}, func(v1, v2 string) bool { result1 := mathutil.MinBy([]string{"a", "ab", "abc"}, func(v1, v2 string) bool {
return len(v1) < len(v2) return len(v1) < len(v2)
}) })
fmt.Println(res1) //a
res2 := mathutil.MinBy([]string{"ab", "ac", "abc"}, func(v1, v2 string) bool { result2 := mathutil.MinBy([]string{"ab", "ac", "abc"}, func(v1, v2 string) bool {
return len(v1) < len(v2) return len(v1) < len(v2)
}) })
fmt.Println(res2) //ab
res3 := mathutil.MinBy([]string{}, func(v1, v2 string) bool { result3 := mathutil.MinBy([]string{}, func(v1, v2 string) bool {
return len(v1) < len(v2) return len(v1) < len(v2)
}) })
fmt.Println(res3) //“”
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// a
// ab
//
} }
``` ```
### <span id="Percent">Percent</span> ### <span id="Percent">Percent</span>
<p>calculate the percentage of val to total, retain n decimal places.</p> <p>calculate the percentage of val to total, retain n decimal places.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -291,6 +345,7 @@ func main() {
```go ```go
func Percent(val, total float64, n int) float64 func Percent(val, total float64, n int) float64
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -302,14 +357,20 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Percent(1, 2, 2)) //0.5 result1 := mathutil.Percent(1, 2, 2)
fmt.Println(mathutil.Percent(0.1, 0.3, 2)) //0.33 result2 := mathutil.Percent(0.1, 0.3, 2)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 0.5
// 0.33
} }
``` ```
### <span id="RoundToFloat">RoundToFloat</span> ### <span id="RoundToFloat">RoundToFloat</span>
<p>Round float up to n decimal places.</p> <p>Round float up to n decimal places.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -317,6 +378,7 @@ func main() {
```go ```go
func RoundToFloat(x float64, n int) float64 func RoundToFloat(x float64, n int) float64
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -328,18 +390,23 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.RoundToFloat(0, 0)) //0 result1 := mathutil.RoundToFloat(0.124, 2)
fmt.Println(mathutil.RoundToFloat(0, 1)) //0 result2 := mathutil.RoundToFloat(0.125, 2)
fmt.Println(mathutil.RoundToFloat(0.124, 2)) //0.12 result3 := mathutil.RoundToFloat(0.125, 3)
fmt.Println(mathutil.RoundToFloat(0.125, 2)) //0.13
fmt.Println(mathutil.RoundToFloat(0.125, 3)) //0.125 fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.12
// 0.13
// 0.125
} }
``` ```
### <span id="RoundToString">RoundToString</span> ### <span id="RoundToString">RoundToString</span>
<p>Round float up to n decimal places. will return string.</p> <p>Round float up to n decimal places. will return string.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -347,6 +414,7 @@ func main() {
```go ```go
func RoundToString(x float64, n int) string func RoundToString(x float64, n int) string
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -358,17 +426,23 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.RoundToString(0, 0)) //"0" result1 := mathutil.RoundToString(0.124, 2)
fmt.Println(mathutil.RoundToString(0, 1)) //"0.0: result2 := mathutil.RoundToString(0.125, 2)
fmt.Println(mathutil.RoundToString(0.124, 2)) //"0.12" result3 := mathutil.RoundToString(0.125, 3)
fmt.Println(mathutil.RoundToString(0.125, 2)) //"0.13"
fmt.Println(mathutil.RoundToString(0.125, 3)) //"0.125" fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.12
// 0.13
// 0.125
} }
``` ```
### <span id="TruncRound">TruncRound</span> ### <span id="TruncRound">TruncRound</span>
<p>Round float off n decimal places.</p> <p>Round float off n decimal places.</p>
<b>Signature:</b> <b>Signature:</b>
@@ -376,6 +450,7 @@ func main() {
```go ```go
func TruncRound(x float64, n int) float64 func TruncRound(x float64, n int) float64
``` ```
<b>Example:</b> <b>Example:</b>
```go ```go
@@ -387,13 +462,17 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.TruncRound(0, 0)) //0 result1 := mathutil.TruncRound(0.124, 2)
fmt.Println(mathutil.TruncRound(0, 1)) //0 result2 := mathutil.TruncRound(0.125, 2)
fmt.Println(mathutil.TruncRound(0.124, 2)) //0.12 result3 := mathutil.TruncRound(0.125, 3)
fmt.Println(mathutil.TruncRound(0.125, 2)) //0.12
fmt.Println(mathutil.TruncRound(0.125, 3)) //0.125 fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.12
// 0.12
// 0.125
} }
``` ```

View File

@@ -1,16 +1,17 @@
# Mathutil # Mathutil
mathutil包实现了一些数学计算的函数.
mathutil 包实现了一些数学计算的函数.
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 源码: ## 源码:
- [https://github.com/duke-git/lancet/blob/main/mathutil/mathutil.go](https://github.com/duke-git/lancet/blob/main/mathutil/mathutil.go) - [https://github.com/duke-git/lancet/blob/main/mathutil/mathutil.go](https://github.com/duke-git/lancet/blob/main/mathutil/mathutil.go)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 用法: ## 用法:
```go ```go
import ( import (
"github.com/duke-git/lancet/v2/mathutil" "github.com/duke-git/lancet/v2/mathutil"
@@ -20,25 +21,26 @@ import (
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## 目录 ## 目录
- [Average](#Average)
- [Exponent](#Exponent) - [Average](#Average)
- [Fibonacci](#Fibonacci) - [Exponent](#Exponent)
- [Factorial](#Factorial) - [Fibonacci](#Fibonacci)
- [Max](#Max) - [Factorial](#Factorial)
- [MaxBy](#MaxBy) - [Max](#Max)
- [Min](#Min) - [MaxBy](#MaxBy)
- [MinBy](#MaxBy) - [Min](#Min)
- [Percent](#Percent) - [MinBy](#MaxBy)
- [RoundToFloat](#RoundToFloat) - [Percent](#Percent)
- [RoundToString](#RoundToString) - [RoundToFloat](#RoundToFloat)
- [TruncRound](#TruncRound) - [RoundToString](#RoundToString)
- [TruncRound](#TruncRound)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
## Documentation ## Documentation
### <span id="Average">Average</span> ### <span id="Average">Average</span>
<p>计算平均数. 可能需要对结果调用RoundToFloat方法四舍五入</p> <p>计算平均数. 可能需要对结果调用RoundToFloat方法四舍五入</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -46,6 +48,7 @@ import (
```go ```go
func Average[T constraints.Integer | constraints.Float](numbers ...T) T func Average[T constraints.Integer | constraints.Float](numbers ...T) T
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -57,15 +60,22 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Average(0, 0)) //0 result1 := mathutil.Average(1, 2)
fmt.Println(mathutil.Average(1, 1)) //1
avg := mathutil.Average(1.2, 1.4) //1.2999999998 avg := mathutil.Average(1.2, 1.4)
roundAvg := mmathutil.RoundToFloat(avg, 1) // 1.3 result2 := mathutil.RoundToFloat(avg, 1)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 1
// 1.3
} }
``` ```
### <span id="Exponent">Exponent</span> ### <span id="Exponent">Exponent</span>
<p>指数计算x的n次方</p> <p>指数计算x的n次方</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -73,6 +83,7 @@ func main() {
```go ```go
func Exponent(x, n int64) int64 func Exponent(x, n int64) int64
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -84,15 +95,23 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Exponent(10, 0)) //1 result1 := mathutil.Exponent(10, 0)
fmt.Println(mathutil.Exponent(10, 1)) //10 result2 := mathutil.Exponent(10, 1)
fmt.Println(mathutil.Exponent(10, 2)) //100 result3 := mathutil.Exponent(10, 2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 1
// 10
// 100
} }
``` ```
### <span id="Fibonacci">Fibonacci</span> ### <span id="Fibonacci">Fibonacci</span>
<p>计算斐波那契数列的第n个数</p> <p>计算斐波那契数列的第n个数</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -100,6 +119,7 @@ func main() {
```go ```go
func Fibonacci(first, second, n int) int func Fibonacci(first, second, n int) int
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -111,17 +131,23 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Fibonacci(1, 1, 1)) //1 result1 := mathutil.Fibonacci(1, 1, 1)
fmt.Println(mathutil.Fibonacci(1, 1, 2)) //1 result2 := mathutil.Fibonacci(1, 1, 2)
fmt.Println(mathutil.Fibonacci(1, 1, 3)) //2 result3 := mathutil.Fibonacci(1, 1, 5)
fmt.Println(mathutil.Fibonacci(1, 1, 4)) //3
fmt.Println(mathutil.Fibonacci(1, 1, 5)) //5 fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 1
// 1
// 5
} }
``` ```
### <span id="Factorial">Factorial</span> ### <span id="Factorial">Factorial</span>
<p>计算阶乘</p> <p>计算阶乘</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -129,6 +155,7 @@ func main() {
```go ```go
func Factorial(x uint) uint func Factorial(x uint) uint
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -140,15 +167,23 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Factorial(0)) //1 result1 := mathutil.Factorial(1)
fmt.Println(mathutil.Factorial(1)) //1 result2 := mathutil.Factorial(2)
fmt.Println(mathutil.Factorial(2)) //2 result3 := mathutil.Factorial(3)
fmt.Println(mathutil.Factorial(3)) //6
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 1
// 2
// 6
} }
``` ```
### <span id="Max">Max</span> ### <span id="Max">Max</span>
<p>返回参数中的最大数</p> <p>返回参数中的最大数</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -156,6 +191,7 @@ func main() {
```go ```go
func Max[T constraints.Integer | constraints.Float](numbers ...T) T func Max[T constraints.Integer | constraints.Float](numbers ...T) T
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -167,22 +203,28 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Max(0, 0)) //0 result1 := mathutil.Max(1, 2, 3)
fmt.Println(mathutil.Max(1, 2, 3)) //3 result2 := mathutil.Max(1.2, 1.4, 1.1, 1.4)
fmt.Println(mathutil.Max(1.2, 1.4, 1.1, 1.4)) //1.4
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 3
// 1.4
} }
``` ```
### <span id="MaxBy">MaxBy</span> ### <span id="MaxBy">MaxBy</span>
<p>使用给定的比较器函数返回切片的最大值</p> <p>使用给定的比较器函数返回切片的最大值</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func MaxBy[T any](slice []T, comparator func(T, T) bool) T func MaxBy[T any](slice []T, comparator func(T, T) bool) T
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -194,27 +236,31 @@ import (
) )
func main() { func main() {
res1 := mathutil.MaxBy([]string{"a", "ab", "abc"}, func(v1, v2 string) bool { result1 := mathutil.MaxBy([]string{"a", "ab", "abc"}, func(v1, v2 string) bool {
return len(v1) > len(v2) return len(v1) > len(v2)
}) })
fmt.Println(res1) //abc
res2 := mathutil.MaxBy([]string{"abd", "abc", "ab"}, func(v1, v2 string) bool { result2 := mathutil.MaxBy([]string{"abd", "abc", "ab"}, func(v1, v2 string) bool {
return len(v1) > len(v2) return len(v1) > len(v2)
}) })
fmt.Println(res2) //abd
res3 := mathutil.MaxBy([]string{}, func(v1, v2 string) bool { result3 := mathutil.MaxBy([]string{}, func(v1, v2 string) bool {
return len(v1) > len(v2) return len(v1) > len(v2)
}) })
fmt.Println(res3) //“”
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// abc
// abd
//
} }
``` ```
### <span id="Min">Min</span> ### <span id="Min">Min</span>
<p>返回参数中的最小数</p> <p>返回参数中的最小数</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -222,6 +268,7 @@ func main() {
```go ```go
func Min[T constraints.Integer | constraints.Float](numbers ...T) T func Min[T constraints.Integer | constraints.Float](numbers ...T) T
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -233,22 +280,28 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Min(0, 0)) //0 result1 := mathutil.Min(1, 2, 3)
fmt.Println(mathutil.Min(1, 2, 3)) //1 result2 := mathutil.Min(1.2, 1.4, 1.1, 1.4)
fmt.Println(mathutil.Min(1.2, 1.4, 1.1, 1.4)) //1.1
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 1
// 1.1
} }
``` ```
### <span id="MinBy">MinBy</span> ### <span id="MinBy">MinBy</span>
<p>使用给定的比较器函数返回切片的最小值</p> <p>使用给定的比较器函数返回切片的最小值</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func MinBy[T any](slice []T, comparator func(T, T) bool) T func MinBy[T any](slice []T, comparator func(T, T) bool) T
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -260,27 +313,31 @@ import (
) )
func main() { func main() {
res1 := mathutil.MinBy([]string{"a", "ab", "abc"}, func(v1, v2 string) bool { result1 := mathutil.MinBy([]string{"a", "ab", "abc"}, func(v1, v2 string) bool {
return len(v1) < len(v2) return len(v1) < len(v2)
}) })
fmt.Println(res1) //a
res2 := mathutil.MinBy([]string{"ab", "ac", "abc"}, func(v1, v2 string) bool { result2 := mathutil.MinBy([]string{"ab", "ac", "abc"}, func(v1, v2 string) bool {
return len(v1) < len(v2) return len(v1) < len(v2)
}) })
fmt.Println(res2) //ab
res3 := mathutil.MinBy([]string{}, func(v1, v2 string) bool { result3 := mathutil.MinBy([]string{}, func(v1, v2 string) bool {
return len(v1) < len(v2) return len(v1) < len(v2)
}) })
fmt.Println(res3) //“”
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// a
// ab
//
} }
``` ```
### <span id="Percent">Percent</span> ### <span id="Percent">Percent</span>
<p>计算百分比保留n位小数</p> <p>计算百分比保留n位小数</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -288,6 +345,7 @@ func main() {
```go ```go
func Percent(val, total float64, n int) float64 func Percent(val, total float64, n int) float64
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -299,14 +357,20 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.Percent(1, 2, 2)) //0.5 result1 := mathutil.Percent(1, 2, 2)
fmt.Println(mathutil.Percent(0.1, 0.3, 2)) //0.33 result2 := mathutil.Percent(0.1, 0.3, 2)
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 0.5
// 0.33
} }
``` ```
### <span id="RoundToFloat">RoundToFloat</span> ### <span id="RoundToFloat">RoundToFloat</span>
<p>四舍五入保留n位小数</p> <p>四舍五入保留n位小数</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -314,6 +378,7 @@ func main() {
```go ```go
func RoundToFloat(x float64, n int) float64 func RoundToFloat(x float64, n int) float64
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -325,18 +390,23 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.RoundToFloat(0, 0)) //0 result1 := mathutil.RoundToFloat(0.124, 2)
fmt.Println(mathutil.RoundToFloat(0, 1)) //0 result2 := mathutil.RoundToFloat(0.125, 2)
fmt.Println(mathutil.RoundToFloat(0.124, 2)) //0.12 result3 := mathutil.RoundToFloat(0.125, 3)
fmt.Println(mathutil.RoundToFloat(0.125, 2)) //0.13
fmt.Println(mathutil.RoundToFloat(0.125, 3)) //0.125 fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.12
// 0.13
// 0.125
} }
``` ```
### <span id="RoundToString">RoundToString</span> ### <span id="RoundToString">RoundToString</span>
<p>四舍五入保留n位小数返回字符串</p> <p>四舍五入保留n位小数返回字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -344,6 +414,7 @@ func main() {
```go ```go
func RoundToString(x float64, n int) string func RoundToString(x float64, n int) string
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -355,17 +426,23 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.RoundToString(0, 0)) //"0" result1 := mathutil.RoundToString(0.124, 2)
fmt.Println(mathutil.RoundToString(0, 1)) //"0.0: result2 := mathutil.RoundToString(0.125, 2)
fmt.Println(mathutil.RoundToString(0.124, 2)) //"0.12" result3 := mathutil.RoundToString(0.125, 3)
fmt.Println(mathutil.RoundToString(0.125, 2)) //"0.13"
fmt.Println(mathutil.RoundToString(0.125, 3)) //"0.125" fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.12
// 0.13
// 0.125
} }
``` ```
### <span id="TruncRound">TruncRound</span> ### <span id="TruncRound">TruncRound</span>
<p>截短n位小数不进行四舍五入</p> <p>截短n位小数不进行四舍五入</p>
<b>函数签名:</b> <b>函数签名:</b>
@@ -373,6 +450,7 @@ func main() {
```go ```go
func TruncRound(x float64, n int) float64 func TruncRound(x float64, n int) float64
``` ```
<b>例子:</b> <b>例子:</b>
```go ```go
@@ -384,13 +462,17 @@ import (
) )
func main() { func main() {
fmt.Println(mathutil.TruncRound(0, 0)) //0 result1 := mathutil.TruncRound(0.124, 2)
fmt.Println(mathutil.TruncRound(0, 1)) //0 result2 := mathutil.TruncRound(0.125, 2)
fmt.Println(mathutil.TruncRound(0.124, 2)) //0.12 result3 := mathutil.TruncRound(0.125, 3)
fmt.Println(mathutil.TruncRound(0.125, 2)) //0.12
fmt.Println(mathutil.TruncRound(0.125, 3)) //0.125 fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.12
// 0.12
// 0.125
} }
``` ```

View File

@@ -64,19 +64,27 @@ import (
) )
func main() { func main() {
s1 := strutil.After("lancet", "") result1 := strutil.After("foo", "")
fmt.Println(s1) //lancet result2 := strutil.After("foo", "foo")
result3 := strutil.After("foo/bar", "foo")
result4 := strutil.After("foo/bar", "/")
result5 := strutil.After("foo/bar/baz", "/")
s2 := strutil.After("github.com/test/lancet", "/") fmt.Println(result1)
fmt.Println(s2) //test/lancet fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
s3 := strutil.After("github.com/test/lancet", "test") // Output:
fmt.Println(s3) // /lancet // foo
//
// /bar
// bar
// bar/baz
} }
``` ```
### <span id="AfterLast">AfterLast</span> ### <span id="AfterLast">AfterLast</span>
<p>Returns the substring after the last occurrence of a specified string in the source string.</p> <p>Returns the substring after the last occurrence of a specified string in the source string.</p>
@@ -94,20 +102,27 @@ import (
) )
func main() { func main() {
s1 := strutil.AfterLast("lancet", "") result1 := strutil.AfterLast("foo", "")
fmt.Println(s1) //lancet result2 := strutil.AfterLast("foo", "foo")
result3 := strutil.AfterLast("foo/bar", "/")
result4 := strutil.AfterLast("foo/bar/baz", "/")
result5 := strutil.AfterLast("foo/bar/foo/baz", "foo")
s2 := strutil.AfterLast("github.com/test/lancet", "/") fmt.Println(result1)
fmt.Println(s2) //lancet fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
s3 := strutil.AfterLast("github.com/test/test/lancet", "test") // Output:
fmt.Println(s3) // /test/lancet // foo
//
// bar
// baz
// /baz
} }
``` ```
### <span id="Before">Before</span> ### <span id="Before">Before</span>
<p>Returns the substring of the source string up to the first occurrence of the specified string.</p> <p>Returns the substring of the source string up to the first occurrence of the specified string.</p>
@@ -125,20 +140,24 @@ import (
) )
func main() { func main() {
s1 := strutil.Before("lancet", "") result1 := strutil.Before("foo", "")
fmt.Println(s1) //lancet result2 := strutil.Before("foo", "foo")
result3 := strutil.Before("foo/bar", "/")
result4 := strutil.Before("foo/bar/baz", "/")
s2 := strutil.Before("github.com/test/lancet", "/") fmt.Println(result1)
fmt.Println(s2) //github.com fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
s3 := strutil.Before("github.com/test/lancet", "test") // Output:
fmt.Println(s3) // github.com/ // foo
//
// foo
// foo
} }
``` ```
### <span id="BeforeLast">BeforeLast</span> ### <span id="BeforeLast">BeforeLast</span>
<p>Returns the substring of the source string up to the last occurrence of the specified string.</p> <p>Returns the substring of the source string up to the last occurrence of the specified string.</p>
@@ -156,18 +175,24 @@ import (
) )
func main() { func main() {
s1 := strutil.BeforeLast("lancet", "") result1 := strutil.BeforeLast("foo", "")
fmt.Println(s1) //lancet result2 := strutil.BeforeLast("foo", "foo")
result3 := strutil.BeforeLast("foo/bar", "/")
result4 := strutil.BeforeLast("foo/bar/baz", "/")
s2 := strutil.BeforeLast("github.com/test/lancet", "/") fmt.Println(result1)
fmt.Println(s2) //github.com/test fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
s3 := strutil.BeforeLast("github.com/test/test/lancet", "test") // Output:
fmt.Println(s3) //github.com/test/ // foo
//
// foo
// foo/bar
} }
``` ```
### <span id="CamelCase">CamelCase</span> ### <span id="CamelCase">CamelCase</span>
<p>Coverts string to camelCase string, non letters and numbers will be ignored.</p> <p>Coverts string to camelCase string, non letters and numbers will be ignored.</p>
@@ -185,25 +210,22 @@ import (
) )
func main() { func main() {
s1 := strutil.CamelCase("foo_bar") strings := []string{"", "foobar", "&FOO:BAR$BAZ", "$foo%", "Foo-#1😄$_%^&*(1bar"}
fmt.Println(s1) //fooBar
s2 := strutil.CamelCase("Foo-Bar") for _, v := range strings {
fmt.Println(s2) //fooBar s := strutil.CamelCase(v)
fmt.Println(s)
s3 := strutil.CamelCase("Foo&bar") }
fmt.Println(s3) //fooBar
s4 := strutil.CamelCase("foo bar")
fmt.Println(s4) //fooBar
s4 := strutil.CamelCase("Foo-#1😄$_%^&*(1bar")
fmt.Println(s4) //foo11Bar
// Output:
//
// foobar
// fooBarBaz
// foo
// foo11Bar
} }
``` ```
### <span id="KebabCase">KebabCase</span> ### <span id="KebabCase">KebabCase</span>
<p>KebabCase covert string to kebab-case, non letters and numbers will be ignored.</p> <p>KebabCase covert string to kebab-case, non letters and numbers will be ignored.</p>
@@ -221,29 +243,29 @@ import (
) )
func main() { func main() {
s1 := strutil.KebabCase("Foo Bar-") strings := []string{"", "foo-bar", "Foo Bar-", "FOOBAR", "Foo-#1😄$_%^&*(1bar"}
fmt.Println(s1) //foo-bar
s2 := strutil.KebabCase("foo_Bar") for _, v := range strings {
fmt.Println(s2) //foo-bar s := strutil.KebabCase(v)
fmt.Println(s)
}
s3 := strutil.KebabCase("fooBar") // Output:
fmt.Println(s3) //foo-bar //
// foo-bar
s4 := strutil.KebabCase("__FOO_BAR__") // foo-bar
fmt.Println(s4) //foo-bar // foobar
// foo-1-1-bar
} }
``` ```
### <span id="UpperKebabCase">UpperKebabCase</span> ### <span id="UpperKebabCase">UpperKebabCase</span>
<p>UpperKebabCase covert string to upper KEBAB-CASE, non letters and numbers will be ignored.</p> <p>UpperKebabCase covert string to upper KEBAB-CASE, non letters and numbers will be ignored.</p>
<b>Signature:</b> <b>Signature:</b>
```go ```go
func KebabCase(s string) string func UpperKebabCase(s string) string
``` ```
<b>Example:</b> <b>Example:</b>
@@ -254,23 +276,22 @@ import (
) )
func main() { func main() {
s1 := strutil.UpperKebabCase("Foo Bar-") strings := []string{"", "foo-bar", "Foo Bar-", "FooBAR", "Foo-#1😄$_%^&*(1bar"}
fmt.Println(s1) //FOO-BAR
s2 := strutil.UpperKebabCase("foo_Bar") for _, v := range strings {
fmt.Println(s2) //FOO-BAR s := strutil.UpperKebabCase(v)
fmt.Println(s)
}
s3 := strutil.UpperKebabCase("fooBar") // Output:
fmt.Println(s3) //FOO-BAR //
// FOO-BAR
s4 := strutil.UpperKebabCase("__FOO_BAR__") // FOO-BAR
fmt.Println(s4) //FOO-BAR // FOO-BAR
// FOO-1-1-BAR
} }
``` ```
### <span id="Capitalize">Capitalize</span> ### <span id="Capitalize">Capitalize</span>
<p>Convert the first character of a string to upper case.</p> <p>Convert the first character of a string to upper case.</p>
@@ -288,19 +309,22 @@ import (
) )
func main() { func main() {
s1 := strutil.Capitalize("foo") strings := []string{"", "Foo", "_foo", "fooBar", "foo-bar"}
fmt.Println(s1) //foo
s2 := strutil.Capitalize("Foo") for _, v := range strings {
fmt.Println(s2) //foo s := strutil.Capitalize(v)
fmt.Println(s)
}
s3 := strutil.Capitalize("FOo" // Output:
fmt.Println(s3) //fOo //
// Foo
// _foo
// Foobar
// Foo-bar
} }
``` ```
### <span id="IsString">IsString</span> ### <span id="IsString">IsString</span>
<p>Check if the value's data type is string.</p> <p>Check if the value's data type is string.</p>
@@ -318,51 +342,27 @@ import (
) )
func main() { func main() {
fmt.Println(strutil.IsString("lancet")) //true result1 := strutil.IsString("")
fmt.Println(strutil.IsString("")) //true result2 := strutil.IsString("a")
result3 := strutil.IsString(1)
result4 := strutil.IsString(true)
result5 := strutil.IsString([]string{"a"})
fmt.Println(strutil.IsString(1)) //false fmt.Println(result1)
fmt.Println(strutil.IsString("")) //false fmt.Println(result2)
fmt.Println(strutil.IsString([]string{})) //false fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// true
// true
// false
// false
// false
} }
``` ```
### <span id="KebabCase">KebabCase</span>
<p>Covert string to kebab-case.</p>
<b>Signature:</b>
```go
func KebabCase(s string) string
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
s1 := strutil.KebabCase("Foo Bar-")
fmt.Println(s1) //foo-bar
s2 := strutil.KebabCase("foo_Bar")
fmt.Println(s2) //foo-bar
s3 := strutil.KebabCase("fooBar")
fmt.Println(s3) //foo-bar
s4 := strutil.KebabCase("__FOO_BAR__")
fmt.Println(s4) //f-o-o-b-a-r
}
```
### <span id="LowerFirst">LowerFirst</span> ### <span id="LowerFirst">LowerFirst</span>
<p>Convert the first character of string to lower case.</p> <p>Convert the first character of string to lower case.</p>
@@ -380,23 +380,21 @@ import (
) )
func main() { func main() {
s1 := strutil.LowerFirst("foo") strings := []string{"", "bar", "BAr", "Bar大"}
fmt.Println(s1) //foo
s2 := strutil.LowerFirst("BAR") for _, v := range strings {
fmt.Println(s2) //bAR s := strutil.LowerFirst(v)
fmt.Println(s)
}
s3 := strutil.LowerFirst("FOo") // Output:
fmt.Println(s3) //fOo //
// bar
s4 := strutil.LowerFirst("fOo大") // bAr
fmt.Println(s4) //fOo // bar
} }
``` ```
### <span id="UpperFirst">UpperFirst</span> ### <span id="UpperFirst">UpperFirst</span>
<p>Convert the first character of string to upper case.</p> <p>Convert the first character of string to upper case.</p>
@@ -414,23 +412,21 @@ import (
) )
func main() { func main() {
s1 := strutil.UpperFirst("foo") strings := []string{"", "bar", "BAr", "bar大"}
fmt.Println(s1) //Foo
s2 := strutil.UpperFirst("bAR") for _, v := range strings {
fmt.Println(s2) //BAR s := strutil.UpperFirst(v)
fmt.Println(s)
}
s3 := strutil.UpperFirst("FOo") // Output:
fmt.Println(s3) //FOo //
// Bar
s4 := strutil.UpperFirst("fOo大") // BAr
fmt.Println(s4) //FOo // Bar
} }
``` ```
### <span id="PadEnd">PadEnd</span> ### <span id="PadEnd">PadEnd</span>
<p>Pads string on the right side if it's shorter than size.</p> <p>Pads string on the right side if it's shorter than size.</p>
@@ -448,23 +444,33 @@ import (
) )
func main() { func main() {
s1 := strutil.PadEnd("a", 1, "b") result1 := strutil.PadEnd("foo", 1, "bar")
fmt.Println(s1) //a result2 := strutil.PadEnd("foo", 2, "bar")
result3 := strutil.PadEnd("foo", 3, "bar")
result4 := strutil.PadEnd("foo", 4, "bar")
result5 := strutil.PadEnd("foo", 5, "bar")
result6 := strutil.PadEnd("foo", 6, "bar")
result7 := strutil.PadEnd("foo", 7, "bar")
s2 := strutil.PadEnd("a", 2, "b") fmt.Println(result1)
fmt.Println(s2) //ab fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
s3 := strutil.PadEnd("abcd", 6, "mno") // Output:
fmt.Println(s3) //abcdmn // foo
// foo
s4 := strutil.PadEnd("abc", 6, "ab") // foo
fmt.Println(s4) //abcaba // foob
// fooba
// foobar
// foobarb
} }
``` ```
### <span id="PadStart">PadStart</span> ### <span id="PadStart">PadStart</span>
<p>Pads string on the left side if it's shorter than size.</p> <p>Pads string on the left side if it's shorter than size.</p>
@@ -482,23 +488,33 @@ import (
) )
func main() { func main() {
s1 := strutil.PadStart("a", 1, "b") result1 := strutil.PadStart("foo", 1, "bar")
fmt.Println(s1) //a result2 := strutil.PadStart("foo", 2, "bar")
result3 := strutil.PadStart("foo", 3, "bar")
result4 := strutil.PadStart("foo", 4, "bar")
result5 := strutil.PadStart("foo", 5, "bar")
result6 := strutil.PadStart("foo", 6, "bar")
result7 := strutil.PadStart("foo", 7, "bar")
s2 := strutil.PadStart("a", 2, "b") fmt.Println(result1)
fmt.Println(s2) //ba fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
s3 := strutil.PadStart("abcd", 6, "mno") // Output:
fmt.Println(s3) //mnabcd // foo
// foo
s4 := strutil.PadStart("abc", 6, "ab") // foo
fmt.Println(s4) //abaabc // bfoo
// bafoo
// barfoo
// barbfoo
} }
``` ```
### <span id="Reverse">Reverse</span> ### <span id="Reverse">Reverse</span>
<p>Return string whose char order is reversed to the given string.</p> <p>Return string whose char order is reversed to the given string.</p>
@@ -516,16 +532,18 @@ import (
) )
func main() { func main() {
s1 := strutil.ReverseStr("abc") s := "foo"
fmt.Println(s1) //cba rs := strutil.Reverse(s)
s2 := strutil.ReverseStr("12345") fmt.Println(s)
fmt.Println(s2) //54321 fmt.Println(rs)
// Output:
// foo
// oof
} }
``` ```
### <span id="SnakeCase">SnakeCase</span> ### <span id="SnakeCase">SnakeCase</span>
<p>Coverts string to snake_case, non letters and numbers will be ignored.</p> <p>Coverts string to snake_case, non letters and numbers will be ignored.</p>
@@ -543,24 +561,22 @@ import (
) )
func main() { func main() {
s1 := strutil.SnakeCase("Foo Bar-") strings := []string{"", "foo-bar", "Foo Bar-", "FOOBAR", "Foo-#1😄$_%^&*(1bar"}
fmt.Println(s1) //foo_bar
s2 := strutil.SnakeCase("foo_Bar") for _, v := range strings {
fmt.Println(s2) //foo_bar s := strutil.SnakeCase(v)
fmt.Println(s)
}
s3 := strutil.SnakeCase("fooBar") // Output:
fmt.Println(s3) //foo_bar //
// foo_bar
s4 := strutil.SnakeCase("__FOO_BAR__") // foo_bar
fmt.Println(s4) //foo_bar // foobar
// foo_1_1_bar
s5 := strutil.SnakeCase("Foo-#1😄$_%^&*(1bar")
fmt.Println(s5) //foo_1_1_bar
} }
``` ```
### <span id="UpperSnakeCase">UpperSnakeCase</span> ### <span id="UpperSnakeCase">UpperSnakeCase</span>
<p>Coverts string to upper KEBAB-CASE, non letters and numbers will be ignored.</p> <p>Coverts string to upper KEBAB-CASE, non letters and numbers will be ignored.</p>
@@ -578,24 +594,22 @@ import (
) )
func main() { func main() {
s1 := strutil.UpperSnakeCase("Foo Bar-") strings := []string{"", "foo-bar", "Foo Bar-", "FooBAR", "Foo-#1😄$_%^&*(1bar"}
fmt.Println(s1) //FOO_BAR
s2 := strutil.UpperSnakeCase("foo_Bar") for _, v := range strings {
fmt.Println(s2) //FOO_BAR s := strutil.UpperSnakeCase(v)
fmt.Println(s)
}
s3 := strutil.UpperSnakeCase("fooBar") // Output:
fmt.Println(s3) //FOO_BAR //
// FOO_BAR
s4 := strutil.UpperSnakeCase("__FOO_BAR__") // FOO_BAR
fmt.Println(s4) //FOO_BAR // FOO_BAR
// FOO_1_1_BAR
s5 := strutil.UpperSnakeCase("Foo-#1😄$_%^&*(1bar")
fmt.Println(s5) //FOO_1_1_BAR
} }
``` ```
### <span id="SplitEx">SplitEx</span> ### <span id="SplitEx">SplitEx</span>
<p>Split a given string whether the result contains empty string.</p> <p>Split a given string whether the result contains empty string.</p>
@@ -613,25 +627,28 @@ import (
) )
func main() { func main() {
arr1 := strutil.SplitEx(" a b c ", "", true) result1 := strutil.SplitEx(" a b c ", "", true)
fmt.Println(arr1) //[]string{}
arr2 := strutil.SplitEx(" a b c ", " ", false) result2 := strutil.SplitEx(" a b c ", " ", false)
fmt.Println(arr2) //[]string{"", "a", "b", "c", ""} result3 := strutil.SplitEx(" a b c ", " ", true)
arr3 := strutil.SplitEx(" a b c ", " ", true) result4 := strutil.SplitEx("a = b = c = ", " = ", false)
fmt.Println(arr3) //[]string{"a", "b", "c"} result5 := strutil.SplitEx("a = b = c = ", " = ", true)
arr4 := strutil.SplitEx(" a = b = c = ", " = ", false) fmt.Println(result1)
fmt.Println(arr4) //[]string{" a", "b", "c", ""} fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
arr5 := strutil.SplitEx(" a = b = c = ", " = ", true) // Output:
fmt.Println(arr5) //[]string{" a", "b", "c"} // []
// [ a b c ]
// [a b c]
// [a b c ]
} }
``` ```
### <span id="Substring">Substring</span> ### <span id="Substring">Substring</span>
<p>Returns a substring of the specified length starting at the specified offset position.</p> <p>Returns a substring of the specified length starting at the specified offset position.</p>
@@ -650,22 +667,26 @@ import (
func main() { func main() {
result1 := strutil.Substring("abcde", 1, 3) result1 := strutil.Substring("abcde", 1, 3)
fmt.Println(result1) //bcd
result2 := strutil.Substring("abcde", 1, 5) result2 := strutil.Substring("abcde", 1, 5)
fmt.Println(result2) //bcde
result3 := strutil.Substring("abcde", -1, 3) result3 := strutil.Substring("abcde", -1, 3)
fmt.Println(result3) //e
result4 := strutil.Substring("abcde", -2, 2) result4 := strutil.Substring("abcde", -2, 2)
fmt.Println(result4) //de
result5 := strutil.Substring("abcde", -2, 3) result5 := strutil.Substring("abcde", -2, 3)
fmt.Println(result5) //de
result6 := strutil.Substring("你好,欢迎你", 0, 2) result6 := strutil.Substring("你好,欢迎你", 0, 2)
fmt.Println(result6) //你好
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
// Output:
// bcd
// bcde
// e
// de
// de
// 你好
} }
``` ```
@@ -686,26 +707,25 @@ import (
) )
func main() { func main() {
s1 := strutil.Wrap("ab", "") result1 := strutil.Wrap("foo", "")
fmt.Println(s1) //ab result2 := strutil.Wrap("foo", "*")
result3 := strutil.Wrap("'foo'", "'")
result4 := strutil.Wrap("", "*")
s2 := strutil.Wrap("", "*") fmt.Println(result1)
fmt.Println(s2) //"" fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
s3 := strutil.Wrap("ab", "*") // Output:
fmt.Println(s3) //*ab* // foo
// *foo*
s4 := strutil.Wrap("ab", "\"") // ''foo''
fmt.Println(s4) //\"ab\" //
s5 := strutil.Wrap("ab", "'")
fmt.Println(s5) //'ab'
} }
``` ```
### <span id="Wrap">Wrap</span> ### <span id="Wrap">Wrap</span>
<p>Unwrap a given string from anther string. will change source string.</p> <p>Unwrap a given string from anther string. will change source string.</p>
@@ -723,20 +743,24 @@ import (
) )
func main() { func main() {
s1 := strutil.Unwrap("ab", "") result1 := strutil.Unwrap("foo", "")
fmt.Println(s1) //ab result2 := strutil.Unwrap("*foo*", "*")
result3 := strutil.Unwrap("*foo", "*")
result4 := strutil.Unwrap("foo*", "*")
result5 := strutil.Unwrap("**foo**", "*")
s2 := strutil.Unwrap("ab", "*") fmt.Println(result1)
fmt.Println(s2) //ab fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
s3 := strutil.Unwrap("**ab**", "*") // Output:
fmt.Println(s3) //*ab* // foo
// foo
s4 := strutil.Unwrap("*ab", "*") // *foo
fmt.Println(s4) //*ab // foo*
// *foo*
s5 := strutil.Unwrap("***", "**")
fmt.Println(s5) //***
} }
``` ```

View File

@@ -49,14 +49,14 @@ import (
### <span id="After">After</span> ### <span id="After">After</span>
<p>返回源字符串中特定字符串首次出现时的位置之后的子字符串</p> <p>返回源字符串中特定字符串首次出现时的位置之后的子字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func After(s, char string) string func After(s, char string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -65,28 +65,36 @@ import (
) )
func main() { func main() {
s1 := strutil.After("lancet", "") result1 := strutil.After("foo", "")
fmt.Println(s1) //lancet result2 := strutil.After("foo", "foo")
result3 := strutil.After("foo/bar", "foo")
result4 := strutil.After("foo/bar", "/")
result5 := strutil.After("foo/bar/baz", "/")
s2 := strutil.After("github.com/test/lancet", "/") fmt.Println(result1)
fmt.Println(s2) //test/lancet fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
s3 := strutil.After("github.com/test/lancet", "test") // Output:
fmt.Println(s3) // /lancet // foo
//
// /bar
// bar
// bar/baz
} }
``` ```
### <span id="AfterLast">AfterLast</span> ### <span id="AfterLast">AfterLast</span>
<p>返回源字符串中指定字符串最后一次出现时的位置之后的子字符串</p> <p>返回源字符串中指定字符串最后一次出现时的位置之后的子字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func AfterLast(s, char string) string func AfterLast(s, char string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -95,29 +103,36 @@ import (
) )
func main() { func main() {
s1 := strutil.AfterLast("lancet", "") result1 := strutil.AfterLast("foo", "")
fmt.Println(s1) //lancet result2 := strutil.AfterLast("foo", "foo")
result3 := strutil.AfterLast("foo/bar", "/")
result4 := strutil.AfterLast("foo/bar/baz", "/")
result5 := strutil.AfterLast("foo/bar/foo/baz", "foo")
s2 := strutil.AfterLast("github.com/test/lancet", "/") fmt.Println(result1)
fmt.Println(s2) //lancet fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
s3 := strutil.AfterLast("github.com/test/test/lancet", "test") // Output:
fmt.Println(s3) // /lancet // foo
//
// bar
// baz
// /baz
} }
``` ```
### <span id="Before">Before</span> ### <span id="Before">Before</span>
<p>返回源字符串中指定字符串第一次出现时的位置之前的子字符串</p> <p>返回源字符串中指定字符串第一次出现时的位置之前的子字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func Before(s, char string) string func Before(s, char string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -126,29 +141,33 @@ import (
) )
func main() { func main() {
s1 := strutil.Before("lancet", "") result1 := strutil.Before("foo", "")
fmt.Println(s1) //lancet result2 := strutil.Before("foo", "foo")
result3 := strutil.Before("foo/bar", "/")
result4 := strutil.Before("foo/bar/baz", "/")
s2 := strutil.Before("github.com/test/lancet", "/") fmt.Println(result1)
fmt.Println(s2) //github.com fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
s3 := strutil.Before("github.com/test/lancet", "test") // Output:
fmt.Println(s3) // github.com/ // foo
//
// foo
// foo
} }
``` ```
### <span id="BeforeLast">BeforeLast</span> ### <span id="BeforeLast">BeforeLast</span>
<p>返回源字符串中指定字符串最后一次出现时的位置之前的子字符串</p> <p>返回源字符串中指定字符串最后一次出现时的位置之前的子字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func BeforeLast(s, char string) string func BeforeLast(s, char string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -157,29 +176,33 @@ import (
) )
func main() { func main() {
s1 := strutil.BeforeLast("lancet", "") result1 := strutil.BeforeLast("foo", "")
fmt.Println(s1) //lancet result2 := strutil.BeforeLast("foo", "foo")
result3 := strutil.BeforeLast("foo/bar", "/")
result4 := strutil.BeforeLast("foo/bar/baz", "/")
s2 := strutil.BeforeLast("github.com/test/lancet", "/") fmt.Println(result1)
fmt.Println(s2) //github.com/test fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
s3 := strutil.BeforeLast("github.com/test/test/lancet", "test") // Output:
fmt.Println(s3) //github.com/test/ // foo
//
// foo
// foo/bar
} }
``` ```
### <span id="CamelCase">CamelCase</span> ### <span id="CamelCase">CamelCase</span>
<p>将字符串转换为驼峰式字符串, 非字母和数字会被忽略</p> <p>将字符串转换为驼峰式字符串, 非字母和数字会被忽略</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func CamelCase(s string) string func CamelCase(s string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -188,35 +211,97 @@ import (
) )
func main() { func main() {
s1 := strutil.CamelCase("foo_bar") strings := []string{"", "foobar", "&FOO:BAR$BAZ", "$foo%", "Foo-#1😄$_%^&*(1bar"}
fmt.Println(s1) //fooBar
s2 := strutil.CamelCase("Foo-Bar") for _, v := range strings {
fmt.Println(s2) //fooBar s := strutil.CamelCase(v)
fmt.Println(s)
}
s3 := strutil.CamelCase("Foo&bar") // Output:
fmt.Println(s3) //fooBar //
// foobar
s4 := strutil.CamelCase("foo bar") // fooBarBaz
fmt.Println(s4) //fooBar // foo
// foo11Bar
s4 := strutil.CamelCase("Foo-#1😄$_%^&*(1bar")
fmt.Println(s4) //foo11Bar
} }
``` ```
### <span id="KebabCase">KebabCase</span>
<p>将字符串转换为kebab-case, 非字母和数字会被忽略。</p>
<b>函数签名:</b>
```go
func KebabCase(s string) string
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
strings := []string{"", "foo-bar", "Foo Bar-", "FOOBAR", "Foo-#1😄$_%^&*(1bar"}
for _, v := range strings {
s := strutil.KebabCase(v)
fmt.Println(s)
}
// Output:
//
// foo-bar
// foo-bar
// foobar
// foo-1-1-bar
}
```
### <span id="UpperKebabCase">UpperKebabCase</span>
<p>将字符串转换为大写KEBAB-CASE, 非字母和数字会被忽略。</p>
<b>函数签名:</b>
```go
func UpperKebabCase(s string) string
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
strings := []string{"", "foo-bar", "Foo Bar-", "FooBAR", "Foo-#1😄$_%^&*(1bar"}
for _, v := range strings {
s := strutil.UpperKebabCase(v)
fmt.Println(s)
}
// Output:
//
// FOO-BAR
// FOO-BAR
// FOO-BAR
// FOO-1-1-BAR
}
```
### <span id="Capitalize">Capitalize</span> ### <span id="Capitalize">Capitalize</span>
<p>将字符串的第一个字符转换为大写</p> <p>将字符串的第一个字符转换为大写</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func Capitalize(s string) string func Capitalize(s string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -225,28 +310,31 @@ import (
) )
func main() { func main() {
s1 := strutil.Capitalize("foo") strings := []string{"", "Foo", "_foo", "fooBar", "foo-bar"}
fmt.Println(s1) //foo
s2 := strutil.Capitalize("Foo") for _, v := range strings {
fmt.Println(s2) //foo s := strutil.Capitalize(v)
fmt.Println(s)
}
s3 := strutil.Capitalize("FOo" // Output:
fmt.Println(s3) //fOo //
// Foo
// _foo
// Foobar
// Foo-bar
} }
``` ```
### <span id="IsString">IsString</span> ### <span id="IsString">IsString</span>
<p>判断传入参数的数据类型是否为字符串</p> <p>判断传入参数的数据类型是否为字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func IsString(v any) bool func IsString(v any) bool
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -255,93 +343,36 @@ import (
) )
func main() { func main() {
fmt.Println(strutil.IsString("lancet")) //true result1 := strutil.IsString("")
fmt.Println(strutil.IsString("")) //true result2 := strutil.IsString("a")
result3 := strutil.IsString(1)
result4 := strutil.IsString(true)
result5 := strutil.IsString([]string{"a"})
fmt.Println(strutil.IsString(1)) //false fmt.Println(result1)
fmt.Println(strutil.IsString("")) //false fmt.Println(result2)
fmt.Println(strutil.IsString([]string{})) //false fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// true
// true
// false
// false
// false
} }
``` ```
### <span id="KebabCase">KebabCase</span>
<p>将字符串转换为kebab-case, 非字母和数字会被忽略</p>
<b>函数签名:</b>
```go
func KebabCase(s string) string
```
<b>例子:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
s1 := strutil.KebabCase("Foo Bar-")
fmt.Println(s1) //foo-bar
s2 := strutil.KebabCase("foo_Bar")
fmt.Println(s2) //foo-bar
s3 := strutil.KebabCase("fooBar")
fmt.Println(s3) //foo-bar
s4 := strutil.KebabCase("__FOO_BAR__")
fmt.Println(s4) //foo-bar
}
```
### <span id="UpperKebabCase">UpperKebabCase</span>
<p>将字符串转换为大写KEBAB-CASE, 非字母和数字会被忽略</p>
<b>函数签名:</b>
```go
func KebabCase(s string) string
```
<b>例子:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
s1 := strutil.UpperKebabCase("Foo Bar-")
fmt.Println(s1) //FOO-BAR
s2 := strutil.UpperKebabCase("foo_Bar")
fmt.Println(s2) //FOO-BAR
s3 := strutil.UpperKebabCase("fooBar")
fmt.Println(s3) //FOO-BAR
s4 := strutil.UpperKebabCase("__FOO_BAR__")
fmt.Println(s4) //FOO-BAR
}
```
### <span id="LowerFirst">LowerFirst</span> ### <span id="LowerFirst">LowerFirst</span>
<p>将字符串的第一个字符转换为小写</p> <p>将字符串的第一个字符转换为小写</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func LowerFirst(s string) string func LowerFirst(s string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -350,32 +381,30 @@ import (
) )
func main() { func main() {
s1 := strutil.LowerFirst("foo") strings := []string{"", "bar", "BAr", "Bar大"}
fmt.Println(s1) //foo
s2 := strutil.LowerFirst("BAR") for _, v := range strings {
fmt.Println(s2) //bAR s := strutil.LowerFirst(v)
fmt.Println(s)
}
s3 := strutil.LowerFirst("FOo") // Output:
fmt.Println(s3) //fOo //
// bar
s4 := strutil.LowerFirst("fOo大") // bAr
fmt.Println(s4) //fOo // bar
} }
``` ```
### <span id="UpperFirst">UpperFirst</span> ### <span id="UpperFirst">UpperFirst</span>
<p>将字符串的第一个字符转换为大写形式</p> <p>将字符串的第一个字符转换为大写形式</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func UpperFirst(s string) string func UpperFirst(s string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -384,32 +413,30 @@ import (
) )
func main() { func main() {
s1 := strutil.UpperFirst("foo") strings := []string{"", "bar", "BAr", "bar大"}
fmt.Println(s1) //Foo
s2 := strutil.UpperFirst("bAR") for _, v := range strings {
fmt.Println(s2) //BAR s := strutil.UpperFirst(v)
fmt.Println(s)
}
s3 := strutil.UpperFirst("FOo") // Output:
fmt.Println(s3) //FOo //
// Bar
s4 := strutil.UpperFirst("fOo大") // BAr
fmt.Println(s4) //FOo // Bar
} }
``` ```
### <span id="PadEnd">PadEnd</span> ### <span id="PadEnd">PadEnd</span>
<p>如果字符串长度短于size则在右侧填充字符串</p> <p>如果字符串长度短于size则在右侧填充字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func PadEnd(source string, size int, padStr string) string func PadEnd(source string, size int, padStr string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -418,32 +445,42 @@ import (
) )
func main() { func main() {
s1 := strutil.PadEnd("a", 1, "b") result1 := strutil.PadEnd("foo", 1, "bar")
fmt.Println(s1) //a result2 := strutil.PadEnd("foo", 2, "bar")
result3 := strutil.PadEnd("foo", 3, "bar")
result4 := strutil.PadEnd("foo", 4, "bar")
result5 := strutil.PadEnd("foo", 5, "bar")
result6 := strutil.PadEnd("foo", 6, "bar")
result7 := strutil.PadEnd("foo", 7, "bar")
s2 := strutil.PadEnd("a", 2, "b") fmt.Println(result1)
fmt.Println(s2) //ab fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
s3 := strutil.PadEnd("abcd", 6, "mno") // Output:
fmt.Println(s3) //abcdmn // foo
// foo
s4 := strutil.PadEnd("abc", 6, "ab") // foo
fmt.Println(s4) //abcaba // foob
// fooba
// foobar
// foobarb
} }
``` ```
### <span id="PadStart">PadStart</span> ### <span id="PadStart">PadStart</span>
<p>如果字符串长度短于size则在左侧填充字符串</p> <p>如果字符串长度短于size则在左侧填充字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func PadStart(source string, size int, padStr string) string func PadStart(source string, size int, padStr string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -452,32 +489,42 @@ import (
) )
func main() { func main() {
s1 := strutil.PadStart("a", 1, "b") result1 := strutil.PadStart("foo", 1, "bar")
fmt.Println(s1) //a result2 := strutil.PadStart("foo", 2, "bar")
result3 := strutil.PadStart("foo", 3, "bar")
result4 := strutil.PadStart("foo", 4, "bar")
result5 := strutil.PadStart("foo", 5, "bar")
result6 := strutil.PadStart("foo", 6, "bar")
result7 := strutil.PadStart("foo", 7, "bar")
s2 := strutil.PadStart("a", 2, "b") fmt.Println(result1)
fmt.Println(s2) //ba fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
s3 := strutil.PadStart("abcd", 6, "mno") // Output:
fmt.Println(s3) //mnabcd // foo
// foo
s4 := strutil.PadStart("abc", 6, "ab") // foo
fmt.Println(s4) //abaabc // bfoo
// bafoo
// barfoo
// barbfoo
} }
``` ```
### <span id="Reverse">Reverse</span> ### <span id="Reverse">Reverse</span>
<p>返回字符顺序与给定字符串相反的字符串</p> <p>返回字符顺序与给定字符串相反的字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func Reverse(s string) string func Reverse(s string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -486,25 +533,27 @@ import (
) )
func main() { func main() {
s1 := strutil.ReverseStr("abc") s := "foo"
fmt.Println(s1) //cba rs := strutil.Reverse(s)
s2 := strutil.ReverseStr("12345") fmt.Println(s)
fmt.Println(s2) //54321 fmt.Println(rs)
// Output:
// foo
// oof
} }
``` ```
### <span id="SnakeCase">SnakeCase</span> ### <span id="SnakeCase">SnakeCase</span>
<p>将字符串转换为snake_case形式, 非字母和数字会被忽略</p> <p>将字符串转换为snake_case形式, 非字母和数字会被忽略</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func SnakeCase(s string) string func SnakeCase(s string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -513,33 +562,31 @@ import (
) )
func main() { func main() {
s1 := strutil.SnakeCase("Foo Bar-") strings := []string{"", "foo-bar", "Foo Bar-", "FOOBAR", "Foo-#1😄$_%^&*(1bar"}
fmt.Println(s1) //foo_bar
s2 := strutil.SnakeCase("foo_Bar") for _, v := range strings {
fmt.Println(s2) //foo_bar s := strutil.SnakeCase(v)
fmt.Println(s)
}
s3 := strutil.SnakeCase("fooBar") // Output:
fmt.Println(s3) //foo_bar //
// foo_bar
s4 := strutil.SnakeCase("__FOO_BAR__") // foo_bar
fmt.Println(s4) //foo_bar // foobar
// foo_1_1_bar
s5 := strutil.SnakeCase("Foo-#1😄$_%^&*(1bar")
fmt.Println(s5) //foo_1_1_bar
} }
``` ```
### <span id="UpperSnakeCase">UpperSnakeCase</span> ### <span id="UpperSnakeCase">UpperSnakeCase</span>
<p>将字符串转换为大写SNAKE_CASE形式, 非字母和数字会被忽略</p> <p>将字符串转换为大写SNAKE_CASE形式, 非字母和数字会被忽略</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func SnakeCase(s string) string func SnakeCase(s string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -548,34 +595,31 @@ import (
) )
func main() { func main() {
s1 := strutil.UpperSnakeCase("Foo Bar-") strings := []string{"", "foo-bar", "Foo Bar-", "FooBAR", "Foo-#1😄$_%^&*(1bar"}
fmt.Println(s1) //FOO_BAR
s2 := strutil.UpperSnakeCase("foo_Bar") for _, v := range strings {
fmt.Println(s2) //FOO_BAR s := strutil.UpperSnakeCase(v)
fmt.Println(s)
}
s3 := strutil.UpperSnakeCase("fooBar") // Output:
fmt.Println(s3) //FOO_BAR //
// FOO_BAR
s4 := strutil.UpperSnakeCase("__FOO_BAR__") // FOO_BAR
fmt.Println(s4) //FOO_BAR // FOO_BAR
// FOO_1_1_BAR
s5 := strutil.UpperSnakeCase("Foo-#1😄$_%^&*(1bar")
fmt.Println(s5) //FOO_1_1_BAR
} }
``` ```
### <span id="SplitEx">SplitEx</span> ### <span id="SplitEx">SplitEx</span>
<p>分割字符串为切片removeEmptyString参数指定是否去除空字符串</p> <p>分割字符串为切片removeEmptyString参数指定是否去除空字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func SplitEx(s, sep string, removeEmptyString bool) []string func SplitEx(s, sep string, removeEmptyString bool) []string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -584,32 +628,37 @@ import (
) )
func main() { func main() {
arr1 := strutil.SplitEx(" a b c ", "", true) result1 := strutil.SplitEx(" a b c ", "", true)
fmt.Println(arr1) //[]string{}
arr2 := strutil.SplitEx(" a b c ", " ", false) result2 := strutil.SplitEx(" a b c ", " ", false)
fmt.Println(arr2) //[]string{"", "a", "b", "c", ""} result3 := strutil.SplitEx(" a b c ", " ", true)
arr3 := strutil.SplitEx(" a b c ", " ", true) result4 := strutil.SplitEx("a = b = c = ", " = ", false)
fmt.Println(arr3) //[]string{"a", "b", "c"} result5 := strutil.SplitEx("a = b = c = ", " = ", true)
arr4 := strutil.SplitEx(" a = b = c = ", " = ", false) fmt.Println(result1)
fmt.Println(arr4) //[]string{" a", "b", "c", ""} fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
arr5 := strutil.SplitEx(" a = b = c = ", " = ", true) // Output:
fmt.Println(arr5) //[]string{" a", "b", "c"} // []
// [ a b c ]
// [a b c]
// [a b c ]
} }
``` ```
### <span id="Substring">Substring</span> ### <span id="Substring">Substring</span>
<p>根据指定的位置和长度截取字符串</p> <p>根据指定的位置和长度截取字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func Substring(s string, offset int, length uint) string func Substring(s string, offset int, length uint) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -619,35 +668,38 @@ import (
func main() { func main() {
result1 := strutil.Substring("abcde", 1, 3) result1 := strutil.Substring("abcde", 1, 3)
fmt.Println(result1) //bcd
result2 := strutil.Substring("abcde", 1, 5) result2 := strutil.Substring("abcde", 1, 5)
fmt.Println(result2) //bcde
result3 := strutil.Substring("abcde", -1, 3) result3 := strutil.Substring("abcde", -1, 3)
fmt.Println(result3) //e
result4 := strutil.Substring("abcde", -2, 2) result4 := strutil.Substring("abcde", -2, 2)
fmt.Println(result4) //de
result5 := strutil.Substring("abcde", -2, 3) result5 := strutil.Substring("abcde", -2, 3)
fmt.Println(result5) //de
result6 := strutil.Substring("你好,欢迎你", 0, 2) result6 := strutil.Substring("你好,欢迎你", 0, 2)
fmt.Println(result6) //你好
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
// Output:
// bcd
// bcde
// e
// de
// de
// 你好
} }
``` ```
### <span id="Wrap">Wrap</span> ### <span id="Wrap">Wrap</span>
<p>用另一个字符串包裹一个字符串</p> <p>用另一个字符串包裹一个字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func Wrap(str string, wrapWith string) string func Wrap(str string, wrapWith string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -656,35 +708,34 @@ import (
) )
func main() { func main() {
s1 := strutil.Wrap("ab", "") result1 := strutil.Wrap("foo", "")
fmt.Println(s1) //ab result2 := strutil.Wrap("foo", "*")
result3 := strutil.Wrap("'foo'", "'")
result4 := strutil.Wrap("", "*")
s2 := strutil.Wrap("", "*") fmt.Println(result1)
fmt.Println(s2) //"" fmt.Println(result2)
fmt.Println(result3)
s3 := strutil.Wrap("ab", "*") fmt.Println(result4)
fmt.Println(s3) //*ab*
// Output:
s4 := strutil.Wrap("ab", "\"") // foo
fmt.Println(s4) //\"ab\" // *foo*
// ''foo''
s5 := strutil.Wrap("ab", "'") //
fmt.Println(s5) //'ab'
} }
``` ```
### <span id="Wrap">Wrap</span>
<p>用另一个字符串解开包裹一个字符串。</p>
### <span id="Unwrap">Unwrap</span>
<p>用另一个字符串解开包裹一个字符串</p>
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func Unwrap(str string, wrapToken string) string func Unwrap(str string, wrapToken string) string
``` ```
<b>例:</b> <b>例:</b>
```go ```go
import ( import (
@@ -693,28 +744,23 @@ import (
) )
func main() { func main() {
s1 := strutil.Unwrap("ab", "") result1 := strutil.Unwrap("foo", "")
fmt.Println(s1) //ab result2 := strutil.Unwrap("*foo*", "*")
result3 := strutil.Unwrap("*foo", "*")
result4 := strutil.Unwrap("foo*", "*")
result5 := strutil.Unwrap("**foo**", "*")
s2 := strutil.Unwrap("ab", "*") fmt.Println(result1)
fmt.Println(s2) //ab fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
s3 := strutil.Unwrap("**ab**", "*") // Output:
fmt.Println(s3) //*ab* // foo
// foo
s4 := strutil.Unwrap("*ab", "*") // *foo
fmt.Println(s4) //*ab // foo*
// *foo*
s5 := strutil.Unwrap("***", "**")
fmt.Println(s5) //***
} }
``` ```

View File

@@ -47,7 +47,7 @@ func Before(n int, fn any) func(args ...any) []reflect.Value {
type CurryFn[T any] func(...T) T type CurryFn[T any] func(...T) T
// New make a curry function for specific value. // New make a curry function for specific value.
// Play: Todo // Play: https://go.dev/play/p/5HopfDwANKX
func (cf CurryFn[T]) New(val T) func(...T) T { func (cf CurryFn[T]) New(val T) func(...T) T {
return func(vals ...T) T { return func(vals ...T) T {
args := append([]T{val}, vals...) args := append([]T{val}, vals...)
@@ -56,7 +56,7 @@ func (cf CurryFn[T]) New(val T) func(...T) T {
} }
// Compose compose the functions from right to left. // Compose compose the functions from right to left.
// Play: Todo // Play: https://go.dev/play/p/KKfugD4PKYF
func Compose[T any](fnList ...func(...T) T) func(...T) T { func Compose[T any](fnList ...func(...T) T) func(...T) T {
return func(args ...T) T { return func(args ...T) T {
firstFn := fnList[0] firstFn := fnList[0]

View File

@@ -114,15 +114,15 @@ func ExampleSchedule() {
count++ count++
} }
stop := Schedule(1*time.Second, increase) stop := Schedule(2*time.Second, increase)
time.Sleep(3 * time.Second) time.Sleep(2 * time.Second)
close(stop) close(stop)
fmt.Println(count) fmt.Println(count)
// Output: // Output:
// 3 // 2
} }
func ExamplePipeline() { func ExamplePipeline() {

View File

@@ -3,7 +3,7 @@ package function
import "time" import "time"
// Watcher is used for record code excution time // Watcher is used for record code excution time
// Play: Todo // Play: https://go.dev/play/p/l2yrOpCLd1I
type Watcher struct { type Watcher struct {
startTime int64 startTime int64
stopTime int64 stopTime int64

View File

@@ -55,7 +55,7 @@ func Factorial(x uint) uint {
} }
// Percent calculate the percentage of value to total. // Percent calculate the percentage of value to total.
// Play: Todo // Play: https://go.dev/play/p/QQM9B13coSP
func Percent(val, total float64, n int) float64 { func Percent(val, total float64, n int) float64 {
if total == 0 { if total == 0 {
return float64(0) return float64(0)

View File

@@ -283,7 +283,7 @@ func SplitEx(s, sep string, removeEmptyString bool) []string {
} }
// Substring returns a substring of the specified length starting at the specified offset position. // Substring returns a substring of the specified length starting at the specified offset position.
// Play: Todo // Play: https://go.dev/play/p/q3sM6ehnPDp
func Substring(s string, offset int, length uint) string { func Substring(s string, offset int, length uint) string {
rs := []rune(s) rs := []rune(s)
size := len(rs) size := len(rs)