Skip to content
Prev Previous commit
Next Next commit
add reduce and reduceWithKeys to EnumeratesValues
  • Loading branch information
mokhosh committed Jan 15, 2021
commit a94adebf49489016e41ba85163f217392f207447
36 changes: 36 additions & 0 deletions src/Illuminate/Collections/Traits/EnumeratesValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,42 @@ public function tap(callable $callback)
return $this;
}

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

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

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;
}

/**
* Create a collection of all elements that do not pass a given truth test.
*
Expand Down