Skip to content

Commit

Permalink
Implement flatMap for Option (#64)
Browse files Browse the repository at this point in the history
* Implement flatMap for Option

* code style fixes
  • Loading branch information
akondas committed Dec 11, 2022
1 parent f854498 commit 4567ce0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Control/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,20 @@ public function map(callable $mapper)
return $this->isEmpty() ? self::none() : self::some($mapper($this->get()));
}

/**
* Maps the value to a new Option if this is a Some, otherwise returns None.
*
* @template U
*
* @param callable(T):Option<U> $mapper
*
* @return Option<U>
*/
public function flatMap(callable $mapper)
{
return $this->isEmpty() ? self::none() : $mapper($this->get());
}

public function isSingleValued(): bool
{
return true;
Expand Down
17 changes: 17 additions & 0 deletions tests/Control/OptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,23 @@ public function testMap(): void
self::assertEquals('MUNUS', $option->map('strtoupper')->get());
}

public function testFlatMapSome(): void
{
$option = Option::of('munus');

self::assertInstanceOf(Option::class, $option->flatMap(fn (string $value) => Option::some($value)));
self::assertEquals('munus', $option->flatMap(fn (string $value) => Option::some($value))->get());
self::assertEquals('2', $option->flatMap(fn () => Option::of('2'))->get());
self::assertTrue(Option::none()->equals($option->flatMap(fn () => Option::none())));
}

public function testFlatMapNone(): void
{
$option = Option::none();

self::assertTrue(Option::none()->equals($option->flatMap(fn (string $value) => Option::some($value))));
}

public function testOptionForEach(): void
{
$lazy = Lazy::ofValue(1);
Expand Down

0 comments on commit 4567ce0

Please sign in to comment.