Skip to content

Commit

Permalink
functions: Add iterable_value_first (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
nilmerg authored Sep 1, 2023
2 parents 1534be2 + df885e7 commit 1150af1
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@ function iterable_key_first($iterable)
return null;
}

/**
* Get the first value of an iterable
*
* @param iterable<mixed> $iterable
*
* @return ?mixed
*/
function iterable_value_first($iterable)
{
foreach ($iterable as $_ => $value) {
return $value;
}

return null;
}

/**
* Yield sets of items from a sorted traversable grouped by a specific criterion gathered from a callback
*
Expand Down
37 changes: 37 additions & 0 deletions tests/FunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -246,4 +246,41 @@ public function testYieldGroupsWithCallbackReturningCriterionValueAndKey()
)
);
}

public function testIterableValueFirstReturnsFirstValueIfIterableImplementsIteratorAndIsNotEmpty()
{
$this->assertSame('a', Stdlib\iterable_value_first(new ArrayIterator(['a', 'b'])));
}

public function testIterableValueFirstReturnsFirstValueIfIterableIsArrayAndIsNotEmpty()
{
$this->assertSame('a', Stdlib\iterable_value_first(['a', 'b']));
}

public function testIterableValueFirstReturnsFirstValueIfIterableIsGeneratorAndIsNotEmpty()
{
$this->assertSame('a', Stdlib\iterable_value_first(call_user_func(function () {
yield 'a';
yield 'b';
})));
}

public function testIterableValueFirstReturnsNullIfIterableImplementsIteratorAndIsEmpty()
{
$this->assertNull(Stdlib\iterable_value_first(new ArrayIterator([])));
}

public function testIterableValueFirstReturnsNullIfIterableIsArrayAndIsEmpty()
{
$this->assertNull(Stdlib\iterable_value_first([]));
}

public function testIterableValueFirstReturnsNullIfIterableIsGeneratorAndIsEmpty()
{
$this->assertNull(Stdlib\iterable_value_first(call_user_func(function () {
return;
/** @noinspection PhpUnreachableStatementInspection Empty generator */
yield;
})));
}
}

0 comments on commit 1150af1

Please sign in to comment.