HH\Lib\Dict\group_by
Requires the Hack Standard Library to be installed.
Facebook Engineer?
This function is available as Dict\group_by()
in Facebook's www repository.
Returns a new dict where
- keys are the results of the given function called on the given values
namespace HH\Lib\Dict;
function group_by<Tk as arraykey, Tv>(
Traversable<Tv> $values,
(function(Tv): ?Tk) $key_func,
): dict<Tk, vec<Tv>>;
- values are vecs of original values that all produced the same key.
If a value produces a null key, it's omitted from the result.
Time complexity: O(n * f), where f is the complexity of $key_func
Space complexity: O(n)
Parameters
Traversable<Tv> $values
(function(Tv): ?Tk) $key_func
Returns
dict<Tk, vec<Tv>>
Examples
Group numbers by their parity (separate even and odd numbers):
$numbers = vec[1, 1, 2, 3, 5, 8, 14];
$groups = Dict\group_by($numbers, $value ==> $value % 2);
\print_r($groups);
Dict
(
[1] => Vec
(
[0] => 1
[1] => 1
[2] => 3
[3] => 5
)
[0] => Vec
(
[0] => 2
[1] => 8
[2] => 14
)
)