mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-06 13:42:28 +08:00
Function: AcceptIf (#198)
AcceptIf returns another function of the same signature as the apply function but also includes a bool value to indicate success or failure. A predicate function that takes an argument of type T and returns a bool. An apply function that also takes an argument of type T and returns a modified value of the same type.
This commit is contained in:
@@ -136,6 +136,27 @@ func Pipeline[T any](funcs ...func(T) T) func(T) T {
|
||||
}
|
||||
}
|
||||
|
||||
// AcceptIf returns another function of the same signature as the apply function but also includes a bool value to indicate success or failure.
|
||||
// A predicate function that takes an argument of type T and returns a bool.
|
||||
// An apply function that also takes an argument of type T and returns a modified value of the same type.
|
||||
func AcceptIf[T any](predicate func(T) bool, apply func(T) T) func(T) (T, bool) {
|
||||
if predicate == nil {
|
||||
panic("programming error: predicate must be not nil")
|
||||
}
|
||||
|
||||
if apply == nil {
|
||||
panic("programming error: apply must be not nil")
|
||||
}
|
||||
|
||||
return func(t T) (T, bool) {
|
||||
if !predicate(t) {
|
||||
var defaultValue T
|
||||
return defaultValue, false
|
||||
}
|
||||
return apply(t), true
|
||||
}
|
||||
}
|
||||
|
||||
func unsafeInvokeFunc(fn any, args ...any) []reflect.Value {
|
||||
fv := reflect.ValueOf(fn)
|
||||
params := make([]reflect.Value, len(args))
|
||||
|
||||
Reference in New Issue
Block a user