Skip to content

Commit 82996c6

Browse files
authored
Merge pull request #6 from simPod/reduce
Introduce iterable_reduce()
2 parents 8a0f64f + 604696e commit 82996c6

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

README.md

+20
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,26 @@ foreach (iterable_map($generator(), 'strtoupper') as $item) {
7272
}
7373
```
7474

75+
iterable_reduce()
76+
--------------
77+
78+
Works like an `reduce` with an `iterable`.
79+
80+
```php
81+
$generator = function () {
82+
yield 1;
83+
yield 2;
84+
};
85+
86+
$reduce = static function ($carry, $item) {
87+
return $carry + $item;
88+
};
89+
90+
var_dump(
91+
iterable_reduce($generator(), $reduce, 0))
92+
); // 3
93+
```
94+
7595
iterable_filter()
7696
--------------
7797

src/iterable-functions.php

+27
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,33 @@ function iterable_filter($iterable, $filter = null)
105105

106106
}
107107

108+
if (!function_exists('iterable_reduce')) {
109+
/**
110+
* Reduces an iterable.
111+
*
112+
* @param iterable<mixed> $iterable
113+
* @param callable(mixed, mixed) $reduce
114+
* @return mixed
115+
*
116+
* @psalm-template TValue
117+
* @psalm-template TResult
118+
*
119+
* @psalm-param iterable<TValue> $iterable
120+
* @psalm-param callable(TResult|null, TValue) $reduce
121+
* @psalm-param TResult|null $initial
122+
*
123+
* @psalm-return TResult|null
124+
*/
125+
function iterable_reduce($iterable, $reduce, $initial = null)
126+
{
127+
foreach ($iterable as $item) {
128+
$initial = $reduce($initial, $item);
129+
}
130+
131+
return $initial;
132+
}
133+
}
134+
108135
/**
109136
* @param iterable|array|\Traversable $iterable
110137
* @param callable|null $filter

tests/TestIterableReduce.php

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
use PHPUnit\Framework\TestCase;
4+
5+
final class TestIterableReduce extends TestCase
6+
{
7+
public function testArrayReduce()
8+
{
9+
$iterable = array(1, 2);
10+
$reduce = static function ($carry, $item) {
11+
return $carry + $item;
12+
};
13+
self::assertSame(3, iterable_reduce($iterable, $reduce, 0));
14+
}
15+
16+
public function testTraversableReduce()
17+
{
18+
$iterable = SplFixedArray::fromArray(array(1, 2));
19+
$reduce = static function ($carry, $item) {
20+
return $carry + $item;
21+
};
22+
self::assertSame(3, iterable_reduce($iterable, $reduce, 0));
23+
}
24+
}

0 commit comments

Comments
 (0)