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

feat(option): new Option::merge() method #425

Closed
wants to merge 1 commit into from
Closed
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
19 changes: 19 additions & 0 deletions src/Psl/Option/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -279,4 +279,23 @@ public function mapOrElse(Closure $closure, Closure $default): Option

return some($default());
}

/**
* Merges an `Option<T>` and other `Option<T>` to `Option<Tu>` by applying a function to both contained values.
*
* @template Tu
*
* @param Option<T> $other
* @param (Closure(T, T): Tu) $closure
*
* @return Option<Tu>
*/
public function merge(Option $other, Closure $closure)
{
if ($this->option !== null && $other->option !== null) {
return some($closure($this->option[0], $other->option[0]));
}

return none();
}
}
21 changes: 21 additions & 0 deletions tests/unit/Option/NoneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,25 @@ public function testAndThen(): void

static::assertNull($option->andThen(static fn($i) => Option\some($i + 1))->unwrapOr(null));
}

/**
* @param Option\Option<int> $value1
* @param Option\Option<int> $value2
*
* @dataProvider provideMerge
*/
public function testMerge(Option\Option $value1, Option\Option $value2): void
{
$this->expectException(NoneException::class);
$this->expectExceptionMessage('Attempting to unwrap a none option.');

$value1->merge($value2, static fn($a, $b) => $a + $b)->unwrap();
}

public function provideMerge(): iterable
{
yield [Option\none(), Option\none()];
yield [Option\none(), Option\some(2)];
yield [Option\some(1), Option\none()];
}
}
8 changes: 8 additions & 0 deletions tests/unit/Option/SomeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,12 @@ public function testAndThen(): void

static::assertSame(3, $option->andThen(static fn($i) => Option\some($i + 1))->unwrapOr(null));
}

public function testMerge(): void
{
$value1 = Option\some(1);
$value2 = Option\some(2);

static::assertSame(3, $value1->merge($value2, static fn($a, $b) => $a + $b)->unwrap());
}
}