Skip to content

Commit

Permalink
Add preserve keys option to the partition method in the collection class
Browse files Browse the repository at this point in the history
  • Loading branch information
sileence committed Dec 3, 2016
1 parent b74eee4 commit 539d044
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
7 changes: 4 additions & 3 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -729,16 +729,17 @@ public function forPage($page, $perPage)
* Partition the collection into two arrays using the given callback or key.
*
* @param callable|string $callback
* @param bool $preserveKeys
* @return array
*/
public function partition($callback)
public function partition($callback, $preserveKeys = false)
{
$partitions = [new static(), new static()];

$callback = $this->valueRetriever($callback);

foreach ($this->items as $item) {
$partitions[(int) ! $callback($item)][] = $item;
foreach ($this->items as $key => $item) {
$partitions[(int) ! $callback($item)][$preserveKeys ? $key : null] = $item;
}

return $partitions;
Expand Down
16 changes: 14 additions & 2 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1655,8 +1655,7 @@ public function testPartitionWithClosure()
public function testPartitionByKey()
{
$courses = new Collection([
['free' => true, 'title' => 'Basic'],
['free' => false, 'title' => 'Premium']
['free' => true, 'title' => 'Basic'], ['free' => false, 'title' => 'Premium'],
]);

list($free, $premium) = $courses->partition('free');
Expand All @@ -1666,6 +1665,19 @@ public function testPartitionByKey()
$this->assertSame($premium->toArray(), [['free' => false, 'title' => 'Premium']]);
}

public function testPartitionPreservingKeys()
{
$courses = new Collection([
'a' => ['free' => true], 'b' => ['free' => false], 'c' => ['free' => true],
]);

list($free, $premium) = $courses->partition('free', true);

$this->assertSame($free->toArray(), ['a' => ['free' => true], 'c' => ['free' => true]]);

$this->assertSame($premium->toArray(), ['b' => ['free' => false]]);
}

public function testPartitionEmptyCollection()
{
$collection = new Collection();
Expand Down

0 comments on commit 539d044

Please sign in to comment.