Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.3] Add partition collection method #16627

Merged
merged 4 commits into from
Dec 3, 2016
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -725,6 +725,24 @@ public function forPage($page, $perPage)
return $this->slice(($page - 1) * $perPage, $perPage);
}

/**
* Output a collection with two elements. Items in the first element did pass
* the given $callback, items in the second element did not.
*
* @param callable $callback
* @return static
*/
public function partition(callable $callback)
{
$partitions = [new static(), new static()];

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

return new static($partitions);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't you just return the plain array so you can separate them using lists?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, changed it to output a plain array.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, list works on collections, so I think we should definitely return a collection.

Really no collection method should ever return a plain array. You don't ever want to break the chain.

}

/**
* Pass the collection to the given callback and return the result.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1640,6 +1640,27 @@ public function testSplitEmptyCollection()
})->toArray()
);
}

public function testPartition()
{
$collection = new Collection(range(1, 10));

$collection = $collection->partition(function ($i) {
return $i <= 5;
});

$this->assertEquals([1, 2, 3, 4, 5], $collection[0]->toArray());
$this->assertEquals([6, 7, 8, 9, 10], $collection[1]->toArray());
}

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

$this->assertCount(2, $collection->partition(function () {
return true;
}));
}
}

class TestAccessorEloquentTestStub
Expand Down