Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add missing Option::orElse method #476

Merged
merged 1 commit into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Psl/Option/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,24 @@ public function or(Option $option): Option
return $option;
}

/**
* Returns the option if it contains a value, otherwise calls $closure and returns the result.
*
* @param (Closure(): Option<T>) $closure
*
* @param-immediately-invoked-callable $closure
*
* @return Option<T>
*/
public function orElse(Closure $closure): Option
{
if ($this->option !== null) {
return $this;
}

return $closure();
}

/**
* Returns none if the option is none, otherwise calls `$predicate` with the wrapped value and returns:
* - Option<T>::some() if `$predicate` returns true (where t is the wrapped value), and
Expand Down
8 changes: 8 additions & 0 deletions tests/unit/Option/NoneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,14 @@ public function testOr(): void
static::assertFalse(Option\none()->or(Option\some(4))->isNone());
}

public function testOrElse(): void
{
static::assertFalse(Option\none()->orElse(static fn () => Option\none())->isSome());
static::assertTrue(Option\none()->orElse(static fn () => Option\some(4))->isSome());
static::assertTrue(Option\none()->orElse(static fn () => Option\none())->isNone());
static::assertFalse(Option\none()->orElse(static fn () => Option\some(4))->isNone());
}

public function testFilter(): void
{
$option = Option\none();
Expand Down
8 changes: 8 additions & 0 deletions tests/unit/Option/SomeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ public function testOr(): void
static::assertFalse(Option\some(2)->or(Option\some(4))->isNone());
}

public function testOrElse(): void
{
static::assertTrue(Option\some(2)->orElse(static fn () => Option\none())->isSome());
static::assertTrue(Option\some(2)->orElse(static fn () => Option\some(4))->isSome());
static::assertFalse(Option\some(2)->orElse(static fn () => Option\none())->isNone());
static::assertFalse(Option\some(2)->orElse(static fn () => Option\some(4))->isNone());
}

public function testFilter(): void
{
$option = Option\some(2);
Expand Down
Loading