Novactive / NovaCollection

Collection implementation that wraps regular PHP arrays.
MIT License
9 stars 3 forks source link

Is there something like hasPosition()? #20

Open nozavroni opened 6 years ago

nozavroni commented 6 years ago

Sometimes I have found it useful to determine if a collection has an item at a certain position, regardless of index/key. I used it in my csv library to be able to easily determine if there was an item in the "3rd" column for instance. Normally I would have to do something like this:

$pos = 3;
// have to call values() to reindex numerically in case the collection has non-numeric keys...
$coll = Factory::create($items)->values();
// now have to do some arithmetic to get correct index
$index = $pos - 1;
if ($coll->hasPosition($index)) {
   $column = $coll->get($index);
}

When I was writing my own collection library I simply implemented these methods to make this process simpler:

$pos = 3;
$coll = Factory::create($items);
if ($coll->hasPosition($pos)) {
    $column = $coll->getPosition($pos);
}

I also made it work with negative numbers to index from the end rather than the beginning.

$coll = Factory::create($items);
// get the second from last item
$coll->getPosition(-2);

@Plopix Do you see any value in this? Your thoughts? Perhaps you already have a solution for something like this? I think the name could be shorter. Something like "hasPos()" and "getPos()".

nozavroni commented 6 years ago

As a matter of fact, in my library, I made getPosition throw an exception so I could make this even simpler:

$items = Factory::create($arr);
try {
    $column = $items->getPosition(-5);
} except (Collection\Exception\InvalidPositionException $e) {
    // there is no fifth-from-last column
}