-
Notifications
You must be signed in to change notification settings - Fork 11.1k
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
[8.x] Add Collection@isSingle method #36428
Conversation
*/ | ||
public function isSingle() | ||
{ | ||
return $this->take(2)->count() === 1; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why is take(2)
necessary? :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@gocanto without it, the whole collection would have to be enumerated, which is a waste.
As soon as we know that there are 2, we know that it's not single!
See this test, which ensures we don't enumerate more than 2 items:
framework/tests/Support/SupportLazyCollectionIsLazyTest.php
Lines 487 to 492 in b72178d
public function testIsSingleIsLazy() | |
{ | |
$this->assertEnumerates(2, function ($collection) { | |
$collection->isSingle(); | |
}); | |
} |
Without take(2)
, this test would fail.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
cool stuff.
idk, seems like overkill to me. if(collect([1])->count() === 1)) is super readable and pretty terse already. |
Taylor updated this to |
If you want syntax improvements to if ($collection->count() === 1)
if ($collection->countIs(1))
if ($collection->count(1))
if ($collection->isSingle())
if ($collection->containsOneItem())
|
$collection->count() === 1;
$collection->containsOneItem(); Hmm. It's even longer than the normal comparison. I find it less readable. +1 for a general method such as |
Adds an
isSingle
method to the collections:Calling
$collection->count() === 1
is so common, I believe it makes sense to have a separate expressive method for it (even more so for the lazy collection, which is a tad more tricky).