Skip to content

Commit 1150af1

Browse files
authored
functions: Add iterable_value_first (#49)
2 parents 1534be2 + df885e7 commit 1150af1

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

src/functions.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,22 @@ function iterable_key_first($iterable)
7272
return null;
7373
}
7474

75+
/**
76+
* Get the first value of an iterable
77+
*
78+
* @param iterable<mixed> $iterable
79+
*
80+
* @return ?mixed
81+
*/
82+
function iterable_value_first($iterable)
83+
{
84+
foreach ($iterable as $_ => $value) {
85+
return $value;
86+
}
87+
88+
return null;
89+
}
90+
7591
/**
7692
* Yield sets of items from a sorted traversable grouped by a specific criterion gathered from a callback
7793
*

tests/FunctionsTest.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,4 +246,41 @@ public function testYieldGroupsWithCallbackReturningCriterionValueAndKey()
246246
)
247247
);
248248
}
249+
250+
public function testIterableValueFirstReturnsFirstValueIfIterableImplementsIteratorAndIsNotEmpty()
251+
{
252+
$this->assertSame('a', Stdlib\iterable_value_first(new ArrayIterator(['a', 'b'])));
253+
}
254+
255+
public function testIterableValueFirstReturnsFirstValueIfIterableIsArrayAndIsNotEmpty()
256+
{
257+
$this->assertSame('a', Stdlib\iterable_value_first(['a', 'b']));
258+
}
259+
260+
public function testIterableValueFirstReturnsFirstValueIfIterableIsGeneratorAndIsNotEmpty()
261+
{
262+
$this->assertSame('a', Stdlib\iterable_value_first(call_user_func(function () {
263+
yield 'a';
264+
yield 'b';
265+
})));
266+
}
267+
268+
public function testIterableValueFirstReturnsNullIfIterableImplementsIteratorAndIsEmpty()
269+
{
270+
$this->assertNull(Stdlib\iterable_value_first(new ArrayIterator([])));
271+
}
272+
273+
public function testIterableValueFirstReturnsNullIfIterableIsArrayAndIsEmpty()
274+
{
275+
$this->assertNull(Stdlib\iterable_value_first([]));
276+
}
277+
278+
public function testIterableValueFirstReturnsNullIfIterableIsGeneratorAndIsEmpty()
279+
{
280+
$this->assertNull(Stdlib\iterable_value_first(call_user_func(function () {
281+
return;
282+
/** @noinspection PhpUnreachableStatementInspection Empty generator */
283+
yield;
284+
})));
285+
}
249286
}

0 commit comments

Comments
 (0)