Skip to content

Commit

Permalink
Arrays::first() & last(): added parameter $else
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Jan 17, 2024
1 parent 526b40c commit 4b3c27e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/Utils/Arrays.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,30 +121,34 @@ public static function contains(array $array, mixed $value): bool


/**
* Returns the first item from the array (matching the specified predicate if given) or null if there is no such item.
* Returns the first item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null.
* The $predicate has the signature `function (mixed $value, int|string $key, array $array): bool`.
* @template T
* @param array<T> $array
* @return ?T
*/
public static function first(array $array, ?callable $predicate = null): mixed
public static function first(array $array, ?callable $predicate = null, ?callable $else = null): mixed
{
$key = self::firstKey($array, $predicate);
return $key === null ? null : $array[$key];
return $key === null
? ($else ? $else() : null)
: $array[$key];
}


/**
* Returns the last item from the array (matching the specified predicate if given) or null if there is no such item.
* Returns the last item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null.
* The $predicate has the signature `function (mixed $value, int|string $key, array $array): bool`.
* @template T
* @param array<T> $array
* @return ?T
*/
public static function last(array $array, ?callable $predicate = null): mixed
public static function last(array $array, ?callable $predicate = null, ?callable $else = null): mixed
{
$key = self::lastKey($array, $predicate);
return $key === null ? null : $array[$key];
return $key === null
? ($else ? $else() : null)
: $array[$key];
}


Expand Down
4 changes: 4 additions & 0 deletions tests/Utils/Arrays.first().phpt
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,7 @@ test('with predicate', function () {
test('predicate arguments', function () {
Arrays::first([2 => 'x'], fn() => Assert::same(['x', 2, [2 => 'x']], func_get_args()));
});

test('else', function () {
Assert::same(123, Arrays::first([], else: fn() => 123));
});
4 changes: 4 additions & 0 deletions tests/Utils/Arrays.last().phpt
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,7 @@ test('with predicate', function () {
test('predicate arguments', function () {
Arrays::last([2 => 'x'], fn() => Assert::same(['x', 2, [2 => 'x']], func_get_args()));
});

test('else', function () {
Assert::same(123, Arrays::last([], else: fn() => 123));
});

0 comments on commit 4b3c27e

Please sign in to comment.