Compare commits

...
4 Commits
Author SHA1 Message Date
dudaodong c88fd3db86 fix: fix go vet issue, method Unwrap() []error 2024-02-20 11:41:58 +08:00
dudaodong 27d19d1717 fix: rename Seek to SeekOffset fix go vet check issue 2024-02-20 11:39:41 +08:00
dudaodong da24bae6b4 doc: add doc for Optional type 2024-02-20 11:22:39 +08:00
donutloop 3cd9d6b68c Add functional predicate (#171)
Enable the execution of assertion functions in a functional manner.
2024-02-20 09:55:39 +08:00
7 changed files with 951 additions and 6 deletions
+1 -3
View File
@@ -3,11 +3,9 @@ on:
push:
branches:
- main
# - v2
pull_request:
branches:
- main
# - v2
jobs:
build:
runs-on: ubuntu-latest
@@ -17,7 +15,7 @@ jobs:
fetch-depth: 2
- uses: actions/setup-go@v2
with:
go-version: "1.18"
go-version: "1.20"
- name: Run coverage
run: go test -v ./... -coverprofile=coverage.txt -covermode=atomic
- name: Run govet
+422
View File
@@ -0,0 +1,422 @@
# Optional
Optional类型代表一个可选的值,它要么包含一个实际值,要么为空。
<div STYLE="page-break-after: always;"></div>
## 源码
- [https://github.com/duke-git/lancet/blob/main/datastructure/optional/optional.go](https://github.com/duke-git/lancet/blob/main/datastructure/optional/optional.go)
<div STYLE="page-break-after: always;"></div>
## 用法
```go
import (
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
```
<div STYLE="page-break-after: always;"></div>
## 目录
- [Of](#Of)
- [OfNullable](#OfNullable)
- [Empty](#Empty)
- [IsPresent](#IsPresent)
- [IsEmpty](#IsEmpty)
- [IfPresent](#IfPresent)
- [IfPresentOrElse](#IfPresentOrElse)
- [Get](#Get)
- [OrElse](#OrElse)
- [OrElseGet](#OrElseGet)
- [OrElseThrow](#OrElseThrow)
<div STYLE="page-break-after: always;"></div>
## 文档
### <span id="Of">Of</span>
<p>返回一个包含非空值的Optional。</p>
<b>函数签名:</b>
```go
func Of[T any](value T) Optional[T]
```
<b>示例:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
value := 42
opt := optional.Of(value)
fmt.Println(opt.Get())
// Output:
// 42
}
```
### <span id="OfNullable">OfNullable</span>
<p>返回一个包含给定值的Optional,该值可能为空 (nil)。</p>
<b>函数签名:</b>
```go
func OfNullable[T any](value *T) Optional[T]
```
<b>示例:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
var value *int = nil
opt := optional.OfNullable(value)
fmt.Println(opt.IsPresent())
value = new(int)
*value = 42
opt = optional.OfNullable(value)
fmt.Println(opt.IsPresent())
// Output:
// false
// true
}
```
### <span id="Empty">Empty</span>
<p>返回一个空Optional实例。</p>
<b>函数签名:</b>
```go
func Empty[T any]() Optional[T]
```
<b>示例:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
optEmpty := OfNullable.Empty[int]()
fmt.Println(optEmpty.IsEmpty())
// Output:
// true
}
```
### <span id="IsEmpty">IsEmpty</span>
<p>验证Optional是否为空。</p>
<b>函数签名:</b>
```go
func (o Optional[T]) IsEmpty() bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
optEmpty := OfNullable.Empty[int]()
fmt.Println(optEmpty.IsEmpty())
// Output:
// true
}
```
### <span id="IsPresent">IsPresent</span>
<p>检查当前Optional内是否存在值。</p>
<b>函数签名:</b>
```go
func (o Optional[T]) IsPresent() bool
```
<b>示例:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
var value *int = nil
opt := optional.OfNullable(value)
fmt.Println(opt.IsPresent())
value = new(int)
*value = 42
opt = optional.OfNullable(value)
fmt.Println(opt.IsPresent())
// Output:
// false
// true
}
```
### <span id="IfPresent">IfPresent</span>
<p>如果值存在,则使用action方法执行给定的操作。</p>
<b>函数签名:</b>
```go
func (o Optional[T]) IfPresent(action func(value T))
```
<b>示例:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
called := false
action := func(value int) { called = true }
optEmpty := optional.Empty[int]()
optEmpty.IfPresent(action)
fmt.Println(called)
called = false // Reset for next test
optWithValue := optional.Of(42)
optWithValue.IfPresent(action)
fmt.Println(optWithValue.IsPresent())
// Output:
// false
// true
}
```
### <span id="IfPresentOrElse">IfPresentOrElse</span>
<p>根据是否存在值执行相应的操作:有值则执行指定操作,没有值则执行默认操作。</p>
<b>函数签名:</b>
```go
func (o Optional[T]) IfPresentOrElse(action func(value T), emptyAction func())
```
<b>示例:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
calledWithValue := false
valueAction := func(value int) { calledWithValue = true }
emptyAction := func() { t.Errorf("Empty action should not be called when value is present") }
optWithValue := optional.Of(42)
optWithValue.IfPresentOrElse(valueAction, emptyAction)
fmt.Println(calledWithValue)
calledWithEmpty := false
valueAction = func(value int) { t.Errorf("Value action should not be called when value is not present") }
emptyAction = func() { calledWithEmpty = true }
optEmpty := optional.Empty[int]()
optEmpty.IfPresentOrElse(valueAction, emptyAction)
fmt.Println(calledWithEmpty)
// Output:
// true
// true
}
```
### <span id="Get">Get</span>
<p>如果存在,返回该值,否则引发panic。</p>
<b>函数签名:</b>
```go
func (o Optional[T]) Get() T
```
<b>示例:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
value := 42
opt := optional.Of(value)
fmt.Println(opt.Get())
// Output:
// 42
}
```
### <span id="OrElse">OrElse</span>
<p>检查Optional值是否存在,如果存在,则直接返回该值。如果不存在,返回参数other值。</p>
<b>函数签名:</b>
```go
func (o Optional[T]) OrElse(other T) T
```
<b>示例:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
optEmpty := optional.Empty[int]()
val := optEmpty.OrElse(100)
fmt.Println(val)
optWithValue := optional.Of(42)
val = optWithValue.OrElse(100)
fmt.Println(val)
// Output:
// 100
// 42
}
```
### <span id="OrElseGet">OrElseGet</span>
<p>检查Optional值是否存在,如果存在,则直接返回该值。如果不存在,则调用一个提供的函数 (supplier),并返回该函数的执行结果。</p>
<b>函数签名:</b>
```go
func (o Optional[T]) OrElseGet(supplier func() T) T
```
<b>示例:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
optEmpty := optional.Empty[int]()
supplier := func() int { return 100 }
val := optEmpty.OrElseGet(supplier)
fmt.Println(val)
// Output:
// 100
}
```
### <span id="OrElseThrow">OrElseThrow</span>
<p>检查Optional值是否存在,如果存在,则直接返回该值,否则返回错误。</p>
<b>函数签名:</b>
```go
func (o Optional[T]) OrElseThrow(errorSupplier func() error) (T, error)
```
<b>示例:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
optEmpty := optional.Empty[int]()
_, err := optEmpty.OrElseThrow(func() error { return errors.New("no value") })
fmt.Println(err.Error())
optWithValue := optional.Of(42)
val, err := optWithValue.OrElseThrow(func() error { return errors.New("no value") })
fmt.Println(val)
fmt.Println(err)
// Output:
// no value
// 42
// nil
}
```
@@ -0,0 +1,416 @@
# Optional
Optional is a type that may or may not contain a non-nil value.
<div STYLE="page-break-after: always;"></div>
## Source
- [https://github.com/duke-git/lancet/blob/main/datastructure/optional/optional.go](https://github.com/duke-git/lancet/blob/main/datastructure/optional/optional.go)
<div STYLE="page-break-after: always;"></div>
## Usage
```go
import (
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
```
<div STYLE="page-break-after: always;"></div>
## Index
- [Of](#Of)
- [OfNullable](#OfNullable)
- [Empty](#Empty)
- [IsPresent](#IsPresent)
- [IsEmpty](#IsEmpty)
- [IfPresent](#IfPresent)
- [IfPresentOrElse](#IfPresentOrElse)
- [Get](#Get)
- [OrElse](#OrElse)
- [OrElseGet](#OrElseGet)
- [OrElseThrow](#OrElseThrow)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="Of">Of</span>
<p>Returns an Optional with a non-nil value.</p>
<b>Signature:</b>
```go
func Of[T any](value T) Optional[T]
```
<b>Example:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
value := 42
opt := optional.Of(value)
fmt.Println(opt.Get())
// Output:
// 42
}
```
### <span id="OfNullable">OfNullable</span>
<p>Returns an Optional for a given value, which may be nil.</p>
<b>Signature:</b>
```go
func OfNullable[T any](value *T) Optional[T]
```
<b>Example:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
var value *int = nil
opt := optional.OfNullable(value)
fmt.Println(opt.IsPresent())
value = new(int)
*value = 42
opt = optional.OfNullable(value)
fmt.Println(opt.IsPresent())
// Output:
// false
// true
}
```
### <span id="Empty">Empty</span>
<p>Returns an empty Optional instance.</p>
<b>Signature:</b>
```go
func Empty[T any]() Optional[T]
```
<b>Example:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
optEmpty := OfNullable.Empty[int]()
fmt.Println(optEmpty.IsEmpty())
// Output:
// true
}
```
### <span id="IsEmpty">IsEmpty</span>
<p>Checks if the Optional is empty.</p>
<b>Signature:</b>
```go
func (o Optional[T]) IsEmpty() bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
optEmpty := OfNullable.Empty[int]()
fmt.Println(optEmpty.IsEmpty())
// Output:
// true
}
```
### <span id="IsPresent">IsPresent</span>
<p>Checks if there is a value present.</p>
<b>Signature:</b>
```go
func (o Optional[T]) IsPresent() bool
```
<b>Example:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
var value *int = nil
opt := optional.OfNullable(value)
fmt.Println(opt.IsPresent())
value = new(int)
*value = 42
opt = optional.OfNullable(value)
fmt.Println(opt.IsPresent())
// Output:
// false
// true
}
```
### <span id="IfPresent">IfPresent</span>
<p>Performs the given action with the value if a value is present.</p>
<b>Signature:</b>
```go
func (o Optional[T]) IfPresent(action func(value T))
```
<b>Example:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
called := false
action := func(value int) { called = true }
optEmpty := optional.Empty[int]()
optEmpty.IfPresent(action)
fmt.Println(called)
called = false // Reset for next test
optWithValue := optional.Of(42)
optWithValue.IfPresent(action)
fmt.Println(optWithValue.IsPresent())
// Output:
// false
// true
}
```
### <span id="IfPresentOrElse">IfPresentOrElse</span>
<p>Performs the action with the value if present, otherwise performs the empty-based action.</p>
<b>Signature:</b>
```go
func (o Optional[T]) IfPresentOrElse(action func(value T), emptyAction func())
```
<b>Example:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
calledWithValue := false
valueAction := func(value int) { calledWithValue = true }
emptyAction := func() { t.Errorf("Empty action should not be called when value is present") }
optWithValue := optional.Of(42)
optWithValue.IfPresentOrElse(valueAction, emptyAction)
fmt.Println(calledWithValue)
calledWithEmpty := false
valueAction = func(value int) { t.Errorf("Value action should not be called when value is not present") }
emptyAction = func() { calledWithEmpty = true }
optEmpty := optional.Empty[int]()
optEmpty.IfPresentOrElse(valueAction, emptyAction)
fmt.Println(calledWithEmpty)
// Output:
// true
// true
}
```
### <span id="Get">Get</span>
<p>Returns the value if present, otherwise panics.</p>
<b>Signature:</b>
```go
func (o Optional[T]) Get() T
```
<b>Example:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
value := 42
opt := optional.Of(value)
fmt.Println(opt.Get())
// Output:
// 42
}
```
### <span id="OrElse">OrElse</span>
<p>Returns the value if present, otherwise returns other.</p>
<b>Signature:</b>
```go
func (o Optional[T]) OrElse(other T) T
```
<b>Example:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
optEmpty := optional.Empty[int]()
val := optEmpty.OrElse(100)
fmt.Println(val)
optWithValue := optional.Of(42)
val = optWithValue.OrElse(100)
fmt.Println(val)
// Output:
// 100
// 42
}
```
### <span id="OrElseGet">OrElseGet</span>
<p>Returns the value if present, otherwise invokes supplier and returns the result.</p>
<b>Signature:</b>
```go
func (o Optional[T]) OrElseGet(supplier func() T) T
```
<b>Example:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
optEmpty := optional.Empty[int]()
supplier := func() int { return 100 }
val := optEmpty.OrElseGet(supplier)
fmt.Println(val)
// Output:
// 100
}
```
### <span id="OrElseThrow">OrElseThrow</span>
<p>Returns the value if present, otherwise returns an error.</p>
<b>Signature:</b>
```go
func (o Optional[T]) OrElseThrow(errorSupplier func() error) (T, error)
```
<b>Example:</b>
```go
package main
import (
"fmt"
optional "github.com/duke-git/lancet/v2/datastructure/optional"
)
func main() {
optEmpty := optional.Empty[int]()
_, err := optEmpty.OrElseThrow(func() error { return errors.New("no value") })
fmt.Println(err.Error())
optWithValue := optional.Of(42)
val, err := optWithValue.OrElseThrow(func() error { return errors.New("no value") })
fmt.Println(val)
fmt.Println(err)
// Output:
// no value
// 42
// nil
}
```
+2 -2
View File
@@ -65,8 +65,8 @@ func (f *FileReader) Offset() int64 {
return f.offset
}
// Seek sets the current offset of the reading
func (f *FileReader) Seek(offset int64) error {
// SeekOffset sets the current offset of the reading
func (f *FileReader) SeekOffset(offset int64) error {
_, err := f.file.Seek(offset, 0)
if err != nil {
return err
+1 -1
View File
@@ -534,7 +534,7 @@ func TestReadlineFile(t *testing.T) {
if !ok {
t.Fail()
}
if err = reader.Seek(offset); err != nil {
if err = reader.SeekOffset(offset); err != nil {
t.Fail()
}
lineRead, err := reader.ReadLine()
+34
View File
@@ -0,0 +1,34 @@
package function
// And returns a composed predicate that represents the logical AND of a list of predicates.
// It evaluates to true only if all predicates evaluate to true for the given value.
func And[T any](predicates ...func(T) bool) func(T) bool {
return func(value T) bool {
for _, predicate := range predicates {
if !predicate(value) {
return false // Short-circuit on the first false predicate
}
}
return true // True if all predicates are true
}
}
// Negate returns a predicate that represents the logical negation of this predicate.
func Negate[T any](predicate func(T) bool) func(T) bool {
return func(value T) bool {
return !predicate(value)
}
}
// Or returns a composed predicate that represents the logical OR of a list of predicates.
// It evaluates to true if at least one of the predicates evaluates to true for the given value.
func Or[T any](predicates ...func(T) bool) func(T) bool {
return func(value T) bool {
for _, predicate := range predicates {
if predicate(value) {
return true // Short-circuit on the first true predicate
}
}
return false // False if all predicates are false
}
}
+75
View File
@@ -0,0 +1,75 @@
package function
import (
"strings"
"testing"
"github.com/duke-git/lancet/v2/internal"
)
func TestPredicatesNegatePure(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestPredicatesNegatePure")
// Define some simple predicates for demonstration
isUpperCase := func(s string) bool {
return strings.ToUpper(s) == s
}
isLowerCase := func(s string) bool {
return strings.ToLower(s) == s
}
isMixedCase := Negate(Or(isUpperCase, isLowerCase))
assert.ShouldBeFalse(isMixedCase("ABC"))
assert.ShouldBeTrue(isMixedCase("AbC"))
}
func TestPredicatesOrPure(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestPredicatesOrPure")
containsDigitOrSpecialChar := Or(
func(s string) bool { return strings.ContainsAny(s, "0123456789") },
func(s string) bool { return strings.ContainsAny(s, "!@#$%") },
)
assert.ShouldBeTrue(containsDigitOrSpecialChar("hello!"))
assert.ShouldBeFalse(containsDigitOrSpecialChar("hello"))
}
func TestPredicatesAndPure(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestPredicatesAndPure")
isNumericAndLength5 := And(
func(s string) bool { return strings.ContainsAny(s, "0123456789") },
func(s string) bool { return len(s) == 5 },
)
assert.ShouldBeTrue(isNumericAndLength5("12345"))
assert.ShouldBeFalse(isNumericAndLength5("1234"))
assert.ShouldBeFalse(isNumericAndLength5("abcde"))
}
func TestPredicatesMix(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestPredicatesMix")
a := Or(
func(s string) bool { return strings.ContainsAny(s, "0123456789") },
func(s string) bool { return strings.ContainsAny(s, "!") },
)
b := And(
func(s string) bool { return strings.ContainsAny(s, "hello") },
func(s string) bool { return strings.ContainsAny(s, "!") },
)
c := Negate(And(a, b))
assert.ShouldBeFalse(c("hello!"))
}