Skip to content

Commit 1f4f6ef

Browse files
authored
Implement findFirst for collection (#94)
1 parent 71ea0e9 commit 1f4f6ef

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/Collection/Traversable.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,14 @@ public function find(callable $predicate): Option
233233
return Option::none();
234234
}
235235

236+
/**
237+
* @return Option<T>
238+
*/
239+
public function findFirst(): Option
240+
{
241+
return $this->isEmpty() ? Option::none() : Option::some($this->head());
242+
}
243+
236244
public function equals($object): bool
237245
{
238246
if ($object === $this) {

tests/Collection/TraversableTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@
55
namespace Munus\Tests\Collection;
66

77
use Munus\Collection\GenericList;
8+
use Munus\Collection\Map;
89
use Munus\Collection\Set;
910
use Munus\Collection\Stream;
1011
use Munus\Control\Option;
1112
use Munus\Exception\UnsupportedOperationException;
13+
use Munus\Tuple;
1214
use PHPUnit\Framework\TestCase;
1315

1416
final class TraversableTest extends TestCase
@@ -145,4 +147,21 @@ public function testNoneMatch(): void
145147
self::assertFalse(GenericList::of(1, 2, 3)->noneMatch(fn (int $v) => $v % 2 === 0));
146148
self::assertFalse(GenericList::of(1)->noneMatch(fn (int $v) => $v % 2 === 1));
147149
}
150+
151+
public function testFindFirstWhenEmpty(): void
152+
{
153+
self::assertTrue(GenericList::empty()->findFirst()->isEmpty());
154+
self::assertTrue(Map::empty()->findFirst()->isEmpty());
155+
self::assertTrue(Set::empty()->findFirst()->isEmpty());
156+
self::assertTrue(Stream::empty()->findFirst()->isEmpty());
157+
}
158+
159+
public function testFindFirstWhenNotEmpty(): void
160+
{
161+
self::assertSame('a', GenericList::of('a', 'b', 'c')->findFirst()->get());
162+
self::assertEquals(Tuple::of('a', 'b'), Map::fromArray(['a' => 'b', 'c' => 'd'])->findFirst()->get());
163+
self::assertSame('a', Set::of('a', 'b', 'c')->findFirst()->get());
164+
self::assertSame('a', Stream::of('a', 'b', 'c')->findFirst()->get());
165+
self::assertSame('a', Stream::iterate('a', fn () => 'a')->findFirst()->get());
166+
}
148167
}

0 commit comments

Comments
 (0)