diff --git a/src/iter.php b/src/iter.php index fe4a945..a11201d 100644 --- a/src/iter.php +++ b/src/iter.php @@ -208,7 +208,7 @@ function filter(callable $predicate, $iterable) { * => 120 * * @param callable $function Reduction function: - * mixed function(mixed $acc, mixed $value) + * mixed function(mixed $acc, mixed $value, mixed $key) * @param array|Traversable $iterable Iterable to reduce * @param mixed $startValue Start value for accumulator. * Usually identity value of $function. @@ -219,8 +219,8 @@ function reduce(callable $function, $iterable, $startValue = null) { _assertIterable($iterable, 'Second argument'); $acc = $startValue; - foreach ($iterable as $value) { - $acc = $function($acc, $value); + foreach ($iterable as $key => $value) { + $acc = $function($acc, $value, $key); } return $acc; } @@ -242,7 +242,7 @@ function reduce(callable $function, $iterable, $startValue = null) { * => iter(1, 2, 6, 24, 120) * * @param callable $function Reduction function: - * mixed function(mixed $acc, mixed $value) + * mixed function(mixed $acc, mixed $value, mixed $key) * @param array|Traversable $iterable Iterable to reduce * @param mixed $startValue Start value for accumulator. * Usually identity value of $function. @@ -253,8 +253,8 @@ function reductions(callable $function, $iterable, $startValue = null) { _assertIterable($iterable, 'Second argument'); $acc = $startValue; - foreach ($iterable as $value) { - $acc = $function($acc, $value); + foreach ($iterable as $key => $value) { + $acc = $function($acc, $value, $key); yield $acc; } } diff --git a/test/iterTest.php b/test/iterTest.php index 036413e..c1f931a 100644 --- a/test/iterTest.php +++ b/test/iterTest.php @@ -134,9 +134,30 @@ public function testReduce() { $this->assertSame(120, reduce(fn\operator('*'), range(1, 5), 1)); } + public function testComplexReduce() { + $this->assertSame('abcdef', reduce(function ($acc, $value, $key) { + return $acc . $key . $value; + }, ['a' => 'b', 'c' => 'd', 'e' => 'f'], '')); + } + public function testReductions() { - $this->assertSame([1, 3, 6, 10, 15], toArrayWithKeys(reductions(fn\operator('+'), range(1, 5), 0))); - $this->assertSame([1, 2, 6, 24, 120], toArrayWithKeys(reductions(fn\operator('*'), range(1, 5), 1))); + $this->assertSame( + [1, 3, 6, 10, 15], + toArrayWithKeys(reductions(fn\operator('+'), range(1, 5), 0)) + ); + $this->assertSame( + [1, 2, 6, 24, 120], + toArrayWithKeys(reductions(fn\operator('*'), range(1, 5), 1)) + ); + } + + public function testComplexReductions() { + $this->assertSame( + ['ab', 'abcd', 'abcdef'], + toArrayWithKeys(reductions(function ($acc, $value, $key) { + return $acc . $key . $value; + }, ['a' => 'b', 'c' => 'd', 'e' => 'f'], '')) + ); } public function testAnyAll() {