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

Support flatMap operation on Map #44

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
26 changes: 26 additions & 0 deletions src/Bonami/Collection/Map.php
Original file line number Diff line number Diff line change
Expand Up @@ -878,6 +878,9 @@ public function __toString(): string
* Constructs a list containing all elements after applying callback
* on each value-key pair from Map
*
* This operation does not follow functor laws, because it returns
* List instead of Map
*
* Complexity: o(n)
*
* @see mapValues - for mapping just values and keeping Map as result
Expand All @@ -896,4 +899,27 @@ public function map(callable $mapper): ArrayList

return ArrayList::fromIterable($mapped);
}

/**
* Constructs a list containing all elements after applying callback
* on each value-key pair from Map and then flattening it.
*
* This operation does not follow monad laws, because it returns
* List instead of Map
*
* Complexity: o(n)
*
* @phpstan-template B
*
* @phpstan-param callable(V, K): iterable<B> $mapper
*
* @phpstan-return ArrayList<B>
*/
public function flatMap(callable $mapper): ArrayList
{
/** @phpstan-var ArrayList<B> */
$flattened = $this->map($mapper)->flatten();

return $flattened;
}
}
12 changes: 12 additions & 0 deletions tests/Bonami/Collection/MapTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,18 @@ public function testMap(): void
self::assertEquals(ArrayList::fromIterable(["a:1", "b:2"]), $mapped);
}

public function testFlatMap(): void
{
$map = new Map([
[1, "a"],
[2, "b"],
]);
$mapped = $map->flatMap(static function (string $value, int $key): Option {
return $key % 2 === 0 ? Option::some("$value:$key") : Option::none();
});
self::assertEquals(ArrayList::fromIterable(["b:2"]), $mapped);
}

public function testMapKeys(): void
{
$map = new Map([
Expand Down