Skip to content

Commit 08dbb8b

Browse files
authored
[8.x] Add reduce with keys to collections and lazy collections (#35839)
* add reduce with keys to collections * add reduce with keys to lazy collections * add test for reduce with keys * fix style
1 parent 374e956 commit 08dbb8b

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

src/Illuminate/Collections/Collection.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -884,6 +884,24 @@ public function reduce(callable $callback, $initial = null)
884884
return array_reduce($this->items, $callback, $initial);
885885
}
886886

887+
/**
888+
* Reduce an associative collection to a single value.
889+
*
890+
* @param callable $callback
891+
* @param mixed $initial
892+
* @return mixed
893+
*/
894+
public function reduceWithKeys(callable $callback, $initial = null)
895+
{
896+
$result = $initial;
897+
898+
foreach ($this->items as $key => $value) {
899+
$result = $callback($result, $value, $key);
900+
}
901+
902+
return $result;
903+
}
904+
887905
/**
888906
* Replace the collection items with the given items.
889907
*

src/Illuminate/Collections/LazyCollection.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -845,6 +845,24 @@ public function reduce(callable $callback, $initial = null)
845845
return $result;
846846
}
847847

848+
/**
849+
* Reduce an associative collection to a single value.
850+
*
851+
* @param callable $callback
852+
* @param mixed $initial
853+
* @return mixed
854+
*/
855+
public function reduceWithKeys(callable $callback, $initial = null)
856+
{
857+
$result = $initial;
858+
859+
foreach ($this as $key => $value) {
860+
$result = $callback($result, $value, $key);
861+
}
862+
863+
return $result;
864+
}
865+
848866
/**
849867
* Replace the collection items with the given items.
850868
*

tests/Support/SupportCollectionTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3592,6 +3592,20 @@ public function testReduce($collection)
35923592
}));
35933593
}
35943594

3595+
/**
3596+
* @dataProvider collectionClassProvider
3597+
*/
3598+
public function testReduceWithKeys($collection)
3599+
{
3600+
$data = new $collection([
3601+
'foo' => 'bar',
3602+
'baz' => 'qux',
3603+
]);
3604+
$this->assertEquals('foobarbazqux', $data->reduceWithKeys(function ($carry, $element, $key) {
3605+
return $carry .= $key.$element;
3606+
}));
3607+
}
3608+
35953609
/**
35963610
* @dataProvider collectionClassProvider
35973611
*/

0 commit comments

Comments
 (0)