Skip to content

Commit

Permalink
[8.x] Add reduce with keys to collections and lazy collections (#35839)
Browse files Browse the repository at this point in the history
* add reduce with keys to collections

* add reduce with keys to lazy collections

* add test for reduce with keys

* fix style
  • Loading branch information
mokhosh committed Jan 12, 2021
1 parent 374e956 commit 08dbb8b
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
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

0 comments on commit 08dbb8b

Please sign in to comment.