Add contains, exists, toArray

- Update docs
This commit is contained in:
2024-07-29 13:58:33 -04:00
parent 57af645d87
commit fad428a4e4
6 changed files with 262 additions and 76 deletions

View File

@@ -103,12 +103,38 @@ readonly class Result
return $this->isError() ? $this : $f($this->getOK());
}
/**
* Does this result's "OK" value match the given value?
*
* @param TOK $value The value to be matched
* @param bool $strict True for strict equality (`===`), false for loose equality (`==`); optional, default is true
* @return bool True if the "OK" value matches the one provided, false otherwise
*/
public function contains(mixed $value, bool $strict = true): bool
{
return match (true) {
$this->isError() => false,
default => $this->okValue->contains($value, $strict),
};
}
/**
* Does the "OK" value of this result match the given predicate function?
*
* @param callable(TOK): bool $f The function to determine whether the value matches
* @return bool True if the OK value matches the function, false otherwise
*/
public function exists(callable $f): bool
{
return $this->isOK() ? $f($this->okValue->get()) : false;
}
/**
* Map an `OK` result to another, leaving an `Error` result unmodified
*
* @template U The type of the mapping function
* @param callable(TOK): U $f The mapping function
* @return Result<U, TError> A transformed `OK` instance or the original `Error` instance
* @template TMapped The type of the mapping function
* @param callable(TOK): TMapped $f The mapping function
* @return Result<TMapped, TError> A transformed `OK` instance or the original `Error` instance
*/
public function map(callable $f): self
{
@@ -118,9 +144,9 @@ readonly class Result
/**
* Map an `Error` result to another, leaving an `OK` result unmodified
*
* @template U The type of the mapping function
* @param callable(TError): U $f The mapping function
* @return Result<TOK, U> A transformed `Error` instance or the original `OK` instance
* @template TMapped The type of the mapping function
* @param callable(TError): TMapped $f The mapping function
* @return Result<TOK, TMapped> A transformed `Error` instance or the original `OK` instance
*/
public function mapError(callable $f): self
{
@@ -139,6 +165,16 @@ readonly class Result
}
}
/**
* Convert this result into a 0 or 1 item array
*
* @return TOK[] An empty array for `Error`, a 1-item array for `OK`
*/
public function toArray(): array
{
return $this->okValue->toArray();
}
/**
* Transform a `Result`'s `OK` value to an `Option`
*