Skip to content

Commit

Permalink
Create a mapToGroups method
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber committed Apr 27, 2017
1 parent 6de58f5 commit 1a36e74
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,25 @@ public function map(callable $callback)
return new static(array_combine($keys, $items));
}

/**
* Run a grouping map over the items.
*
* The callback should return an associative array with a single key/value pair.
*
* @param callable $callback
* @return static
*/
public function mapToGroups(callable $callback)
{
$groups = $this->map($callback)->reduce(function ($groups, $pair) {
$groups[key($pair)][] = reset($pair);

return $groups;
}, []);

return (new static($groups))->map([$this, 'make']);
}

/**
* Run an associative map over each of the items.
*
Expand Down
29 changes: 29 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1049,6 +1049,35 @@ public function testFlatMap()
$this->assertEquals(['programming', 'basketball', 'music', 'powerlifting'], $data->all());
}

public function testMapToGroups()
{
$data = new Collection([
['id' => 1, 'name' => 'A'],
['id' => 2, 'name' => 'B'],
['id' => 3, 'name' => 'C'],
['id' => 4, 'name' => 'B'],
]);

$groups = $data->mapToGroups(function ($item, $key) {
return [$item['name'] => $item['id']];
});

$this->assertInstanceOf(Collection::class, $groups);
$this->assertEquals(['A' => [1], 'B' => [2, 4], 'C' => [3]], $groups->toArray());
$this->assertInstanceOf(Collection::class, $groups['A']);
}

public function testMapToGroupsWithNumericKeys()
{
$data = new Collection([1, 2, 3, 2, 1]);

$groups = $data->mapToGroups(function ($item, $key) {
return [$item => $key];
});

$this->assertEquals([1 => [0, 4], 2 => [1, 3], 3 => [2]], $groups->toArray());
}

public function testMapWithKeys()
{
$data = new Collection([
Expand Down

0 comments on commit 1a36e74

Please sign in to comment.