Skip to content

Commit

Permalink
Added Utils::groupBy as a convenience tool
Browse files Browse the repository at this point in the history
  • Loading branch information
vladar committed Sep 6, 2015
1 parent c312f73 commit 25c42e6
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ public static function find($traversable, callable $predicate)
return null;
}

/**
* @param $traversable
* @param callable $predicate
* @return array
* @throws \Exception
*/
public static function filter($traversable, callable $predicate)
{
self::invariant(is_array($traversable) || $traversable instanceof \Traversable, __METHOD__ . ' expects array or Traversable');
Expand Down Expand Up @@ -100,6 +106,37 @@ public static function keyMap($traversable, callable $keyFn)
return $map;
}

/**
* Splits original traversable to several arrays with keys equal to $keyFn return
*
* E.g. Utils::groupBy([1, 2, 3, 4, 5], function($value) {return $value % 3}) will output:
* [
* 1 => [1, 4],
* 2 => [2, 5],
* 0 => [3],
* ]
*
* $keyFn is also allowed to return array of keys. Then value will be added to all arrays with given keys
*
* @param $traversable
* @param callable $keyFn function($value, $key) => $newKey(s)
* @return array
*/
public static function groupBy($traversable, callable $keyFn)
{
self::invariant(is_array($traversable) || $traversable instanceof \Traversable, __METHOD__ . ' expects array or Traversable');

$grouped = [];
foreach ($traversable as $key => $value) {
$newKeys = (array) $keyFn($value, $key);
foreach ($newKeys as $key) {
$grouped[$key][] = $value;
}
}

return $grouped;
}

/**
* @param $test
* @param string $message
Expand Down

0 comments on commit 25c42e6

Please sign in to comment.