[8.x] Add Collection@isSingle method#36428
Conversation
| */ | ||
| public function isSingle() | ||
| { | ||
| return $this->take(2)->count() === 1; |
There was a problem hiding this comment.
why is take(2) necessary? :)
There was a problem hiding this comment.
@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
Without take(2), this test would fail.
|
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
isSinglemethod to the collections:Calling
$collection->count() === 1is 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).