Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Pass $key to closure in Collection and LazyCollection's reduce method as well #35878

Merged
merged 11 commits into from Jan 15, 2021
8 changes: 7 additions & 1 deletion src/Illuminate/Collections/Collection.php
Expand Up @@ -881,7 +881,13 @@ public function random($number = null)
*/
public function reduce(callable $callback, $initial = null)
{
return array_reduce($this->items, $callback, $initial);
$result = $initial;

foreach ($this->items as $key => $value) {
$result = $callback($result, $value, $key);
}

return $result;
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/Illuminate/Collections/LazyCollection.php
Expand Up @@ -838,8 +838,8 @@ public function reduce(callable $callback, $initial = null)
{
$result = $initial;

foreach ($this as $value) {
$result = $callback($result, $value);
foreach ($this as $key => $value) {
$result = $callback($result, $value, $key);
}

return $result;
Expand Down
2 changes: 1 addition & 1 deletion tests/Support/SupportCollectionTest.php
Expand Up @@ -3601,7 +3601,7 @@ public function testReduceWithKeys($collection)
'foo' => 'bar',
'baz' => 'qux',
]);
$this->assertEquals('foobarbazqux', $data->reduceWithKeys(function ($carry, $element, $key) {
$this->assertEquals('foobarbazqux', $data->reduce(function ($carry, $element, $key) {
return $carry .= $key.$element;
}));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Since we're still keeping reduceWithKeys around till 9.x (because it was already tagged), we shouldn't remove its test.
  2. You can just add the $key to the other test. No need for 2 separate tests.
  3. As discussed on that other PR, you can move the reduce method into the EnumeratesValues trait.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do, thanks for the comment

}
Expand Down