Skip to content

Commit 25c42e6

Browse files
committed
Added Utils::groupBy as a convenience tool
1 parent c312f73 commit 25c42e6

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/Utils.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,12 @@ public static function find($traversable, callable $predicate)
4545
return null;
4646
}
4747

48+
/**
49+
* @param $traversable
50+
* @param callable $predicate
51+
* @return array
52+
* @throws \Exception
53+
*/
4854
public static function filter($traversable, callable $predicate)
4955
{
5056
self::invariant(is_array($traversable) || $traversable instanceof \Traversable, __METHOD__ . ' expects array or Traversable');
@@ -100,6 +106,37 @@ public static function keyMap($traversable, callable $keyFn)
100106
return $map;
101107
}
102108

109+
/**
110+
* Splits original traversable to several arrays with keys equal to $keyFn return
111+
*
112+
* E.g. Utils::groupBy([1, 2, 3, 4, 5], function($value) {return $value % 3}) will output:
113+
* [
114+
* 1 => [1, 4],
115+
* 2 => [2, 5],
116+
* 0 => [3],
117+
* ]
118+
*
119+
* $keyFn is also allowed to return array of keys. Then value will be added to all arrays with given keys
120+
*
121+
* @param $traversable
122+
* @param callable $keyFn function($value, $key) => $newKey(s)
123+
* @return array
124+
*/
125+
public static function groupBy($traversable, callable $keyFn)
126+
{
127+
self::invariant(is_array($traversable) || $traversable instanceof \Traversable, __METHOD__ . ' expects array or Traversable');
128+
129+
$grouped = [];
130+
foreach ($traversable as $key => $value) {
131+
$newKeys = (array) $keyFn($value, $key);
132+
foreach ($newKeys as $key) {
133+
$grouped[$key][] = $value;
134+
}
135+
}
136+
137+
return $grouped;
138+
}
139+
103140
/**
104141
* @param $test
105142
* @param string $message

0 commit comments

Comments
 (0)