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] Add reduce with keys to collections and lazy collections #35839

Merged
merged 4 commits into from Jan 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Illuminate/Collections/Collection.php
Expand Up @@ -884,6 +884,24 @@ public function reduce(callable $callback, $initial = null)
return array_reduce($this->items, $callback, $initial);
}

/**
* Reduce an associative collection to a single value.
*
* @param callable $callback
* @param mixed $initial
* @return mixed
*/
public function reduceWithKeys(callable $callback, $initial = null)
{
$result = $initial;

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

return $result;
}

/**
* Replace the collection items with the given items.
*
Expand Down
18 changes: 18 additions & 0 deletions src/Illuminate/Collections/LazyCollection.php
Expand Up @@ -845,6 +845,24 @@ public function reduce(callable $callback, $initial = null)
return $result;
}

/**
* Reduce an associative collection to a single value.
*
* @param callable $callback
* @param mixed $initial
* @return mixed
*/
public function reduceWithKeys(callable $callback, $initial = null)
{
$result = $initial;

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

return $result;
}

/**
* Replace the collection items with the given items.
*
Expand Down
14 changes: 14 additions & 0 deletions tests/Support/SupportCollectionTest.php
Expand Up @@ -3592,6 +3592,20 @@ public function testReduce($collection)
}));
}

/**
* @dataProvider collectionClassProvider
*/
public function testReduceWithKeys($collection)
{
$data = new $collection([
'foo' => 'bar',
'baz' => 'qux',
]);
$this->assertEquals('foobarbazqux', $data->reduceWithKeys(function ($carry, $element, $key) {
return $carry .= $key.$element;
}));
}

/**
* @dataProvider collectionClassProvider
*/
Expand Down