Skip to content

Commit b28d156

Browse files
test sum
1 parent e0e86fe commit b28d156

File tree

4 files changed

+73
-15
lines changed

4 files changed

+73
-15
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454
"src/RemoveKey.php",
5555
"src/Set.php",
5656
"src/Some.php",
57-
"src/array_functions.php"
57+
"src/Sum.php"
5858
]
5959
},
6060
"autoload-dev": {

src/Sum.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace BrenoRoosevelt;
5+
6+
/**
7+
* Sums the values returned by the callabck function for each element in the collection
8+
*
9+
* @param iterable $items The collection
10+
* @param callable $callback The callable that must return int or float value
11+
* @param int $mode [optional] <p>
12+
* Flag determining what arguments are sent to <i>callback</i>:
13+
* </p><ul>
14+
* <li>
15+
* <b>CALLBACK_USE_VALUE</b> - <b>default</b> pass value as the only argument
16+
* </li>
17+
* <li>
18+
* <b>CALLBACK_USE_KEY</b> - pass key as the only argument
19+
* to <i>callback</i> instead of the value</span>
20+
* </li>
21+
* <li>
22+
* <b>CALLBACK_USE_BOTH</b> - pass both value and key as
23+
* arguments to <i>callback</i></span>
24+
* </li>
25+
* </ul>
26+
* @return array
27+
*/
28+
function sum(iterable $items, callable $callback, int $mode = 0)
29+
{
30+
$sum = 0;
31+
foreach ($items as $key => $value) {
32+
$sum += call_user_func_array($callback, __args($mode, $key, $value));
33+
}
34+
35+
return $sum;
36+
}

src/array_functions.php

Lines changed: 0 additions & 14 deletions
This file was deleted.

tests/SumTest.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace BrenoRoosevelt\Tests;
5+
6+
use PHPUnit\Framework\TestCase;
7+
use function BrenoRoosevelt\sum;
8+
use const BrenoRoosevelt\CALLBACK_USE_BOTH;
9+
use const BrenoRoosevelt\CALLBACK_USE_KEY;
10+
11+
class SumTest extends TestCase
12+
{
13+
public function testSum()
14+
{
15+
$elements = [1, 2, 3];
16+
$this->assertEquals(15, sum($elements, fn($v) => 5));
17+
}
18+
19+
public function testSumValues()
20+
{
21+
$elements = [1, 2, 3];
22+
$this->assertEquals(6, sum($elements, fn($v) => $v));
23+
}
24+
25+
public function testSumKeys()
26+
{
27+
$elements = [1, 2, 3];
28+
$this->assertEquals(3, sum($elements, fn($k) => $k, CALLBACK_USE_KEY));
29+
}
30+
31+
public function testSumBoth()
32+
{
33+
$elements = [1, 2, 3];
34+
$this->assertEquals(9, sum($elements, fn($v, $k) => $k + $v, CALLBACK_USE_BOTH));
35+
}
36+
}

0 commit comments

Comments
 (0)