Skip to content

Commit 35dfa27

Browse files
committed
Add Collection.findLast function
1 parent f9c37da commit 35dfa27

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/Collection/findLast.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* This file is part of the SolidWorx Lodash-PHP project.
7+
*
8+
* @author Pierre du Plessis <open-source@solidworx.co>
9+
* @copyright Copyright (c) 2017
10+
*/
11+
12+
namespace _;
13+
14+
use function _\internal\baseIteratee;
15+
16+
/**
17+
* This method is like `find` except that it iterates over elements of
18+
* `collection` from right to left.
19+
*
20+
* @category Collection
21+
* @param iterable $collection The collection to inspect.
22+
* @param callable $predicate The function invoked per iteration.
23+
* @param int $fromIndex The index to search from.
24+
* @return mixed Returns the matched element, else `undefined`.
25+
* @example
26+
* <code>
27+
* findLast([1, 2, 3, 4], function ($n) { return $n % 2 == 1; })
28+
* // => 3
29+
* </cdoe>
30+
*/
31+
function findLast(iterable $collection, $predicate = null, int $fromIndex = 0)
32+
{
33+
if (null === $predicate) {
34+
$predicate = '_\identity';
35+
}
36+
37+
$iteratee = baseIteratee($predicate);
38+
39+
foreach (\array_slice(\array_reverse($collection, true), $fromIndex) as $key => $value) {
40+
if ($iteratee($value, $key, $collection)) {
41+
return $value;
42+
}
43+
}
44+
45+
return null;
46+
}

tests/Collection/FindLastTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* This file is part of the SolidWorx Lodash-PHP project.
7+
*
8+
* @author Pierre du Plessis <open-source@solidworx.co>
9+
* @copyright Copyright (c) 2017
10+
*/
11+
12+
use PHPUnit\Framework\TestCase;
13+
use function _\findLast;
14+
15+
class FindLastTest extends TestCase
16+
{
17+
public function testFindLast()
18+
{
19+
$this->assertSame(3, findLast([1, 2, 3, 4], function ($n) { return $n % 2 == 1; }));
20+
}
21+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy