Simplify predicate-based functions

This commit is contained in:
Michael Bull 2024-03-08 20:36:09 +00:00
parent 0b85cc2aad
commit f208f5ee79
3 changed files with 18 additions and 43 deletions

View File

@ -251,14 +251,9 @@ public inline fun <V, E> Result<V, E>.toErrorIf(predicate: (V) -> Boolean, trans
callsInPlace(transform, InvocationKind.AT_MOST_ONCE) callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
} }
return when (this) { return when {
is Ok -> if (predicate(value)) { this is Ok && predicate(value) -> Err(transform(value))
Err(transform(value)) else -> this
} else {
this
}
is Err -> this
} }
} }

View File

@ -62,13 +62,9 @@ public inline fun <V, E : Throwable> Result<V, E>.throwIf(predicate: (E) -> Bool
callsInPlace(predicate, InvocationKind.AT_MOST_ONCE) callsInPlace(predicate, InvocationKind.AT_MOST_ONCE)
} }
return when (this) { return when {
is Ok -> this this is Err && predicate(error) -> throw error
is Err -> if (predicate(error)) { else -> this
throw error
} else {
this
}
} }
} }

View File

@ -43,13 +43,9 @@ public inline fun <V, E> Result<V, E>.recoverIf(predicate: (E) -> Boolean, trans
callsInPlace(transform, InvocationKind.AT_MOST_ONCE) callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
} }
return when (this) { return when {
is Ok -> this this is Err && predicate(error) -> Ok(transform(error))
is Err -> if (predicate(error)) { else -> this
Ok(transform(error))
} else {
this
}
} }
} }
@ -63,13 +59,9 @@ public inline fun <V, E> Result<V, E>.recoverUnless(predicate: (E) -> Boolean, t
callsInPlace(transform, InvocationKind.AT_MOST_ONCE) callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
} }
return when (this) { return when {
is Ok -> this this is Err && !predicate(error) -> Ok(transform(error))
is Err -> if (!predicate(error)) { else -> this
Ok(transform(error))
} else {
this
}
} }
} }
@ -101,13 +93,9 @@ public inline fun <V, E> Result<V, E>.andThenRecoverIf(
callsInPlace(transform, InvocationKind.AT_MOST_ONCE) callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
} }
return when (this) { return when {
is Ok -> this this is Err && predicate(error) -> transform(error)
is Err -> if (predicate(error)) { else -> this
transform(error)
} else {
this
}
} }
} }
@ -124,12 +112,8 @@ public inline fun <V, E> Result<V, E>.andThenRecoverUnless(
callsInPlace(transform, InvocationKind.AT_MOST_ONCE) callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
} }
return when (this) { return when {
is Ok -> this this is Err && !predicate(error) -> transform(error)
is Err -> if (!predicate(error)) { else -> this
transform(error)
} else {
this
}
} }
} }