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

doc: normalize documents

This commit is contained in:
dudaodong
2023-01-13 14:36:33 +08:00
parent 2c6e9a3fb9
commit 4c5524354c
12 changed files with 1800 additions and 1211 deletions

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
} }
``` ```