1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Novactive Collection. |
4
|
|
|
* |
5
|
|
|
* @author Luke Visinoni <[email protected], [email protected]> |
6
|
|
|
* @author Sébastien Morel <[email protected], [email protected]> |
7
|
|
|
* @copyright 2017 Novactive |
8
|
|
|
* @license MIT |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Novactive\Tests; |
12
|
|
|
|
13
|
|
|
use Novactive\Collection\Factory; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class ReduceCollectionTest. |
17
|
|
|
*/ |
18
|
|
|
class ReduceCollectionTest extends UnitTestCase |
19
|
|
|
{ |
20
|
|
|
public function testReduceIterativelyReducesCollectionToASingleValue() |
21
|
|
|
{ |
22
|
|
|
$coll = Factory::create($this->fixtures['names']); |
23
|
|
|
|
24
|
|
|
$count = function ($carry, $val, $key = null) { |
25
|
|
|
return ++$carry; |
26
|
|
|
}; |
27
|
|
|
|
28
|
|
|
$concat = function ($carry, $val, $key = null) { |
29
|
|
|
return $carry.$val; |
30
|
|
|
}; |
31
|
|
|
|
32
|
|
|
$concateven = function ($carry, $val, $key) { |
33
|
|
|
if ($key % 2 == 0) { |
34
|
|
|
$carry .= $val; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return $carry; |
38
|
|
|
}; |
39
|
|
|
|
40
|
|
|
$this->assertEquals(10, $coll->reduce($count)); |
41
|
|
|
$this->assertEquals('ChelseaAdellaMonteMayeLottieDonDaytonKirkTroyNakia', $coll->reduce($concat)); |
42
|
|
|
|
43
|
|
|
if (!$coll instanceof \Novactive\Tests\Perfs\ArrayMethodCollection) { |
44
|
|
|
$this->assertEquals('ChelseaMonteLottieDaytonTroy', $coll->reduce($concateven)); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function testImplodeCollection() |
49
|
|
|
{ |
50
|
|
|
$coll = Factory::create($this->fixtures['names']); |
51
|
|
|
|
52
|
|
|
$return = $coll->implode(';'); |
53
|
|
|
|
54
|
|
|
$reduction = function ($carry, $val, $key = null) { |
55
|
|
|
if (!empty($carry)) { |
56
|
|
|
return $carry.';'.$val; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $val; |
60
|
|
|
}; |
61
|
|
|
|
62
|
|
|
$return2 = $coll->reduce($reduction); |
63
|
|
|
|
64
|
|
|
$this->assertEquals($return, $return2); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|