Skip to content

Commit 684c427

Browse files
TheAlexLichtersebastiandedeyne
authored andcommitted
Add byIndex macro (#87)
* Add byIndex macro * Rename byIndex to at
1 parent 6a7b590 commit 684c427

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/macros/at.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
use Illuminate\Support\Collection;
4+
5+
/**
6+
* Get a single item from the collection by index.
7+
*
8+
* @param mixed $index
9+
*
10+
* @return mixed
11+
*/
12+
Collection::macro('at', function ($index) {
13+
return $this->slice($index, 1)->first();
14+
});

tests/AtTest.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
namespace Spatie\CollectionMacros\Test;
4+
5+
use Illuminate\Support\Collection;
6+
7+
class AtTest extends TestCase
8+
{
9+
/** @test */
10+
public function it_retrieves_an_item_by_positive_index()
11+
{
12+
$data = new Collection([1, 2, 3]);
13+
14+
$this->assertEquals(2, $data->at(1));
15+
}
16+
17+
/** @test */
18+
public function it_retrieves_an_item_by_negative_index()
19+
{
20+
$data = new Collection([1, 2, 3]);
21+
22+
$this->assertEquals(3, $data->at(-1));
23+
}
24+
25+
/** @test */
26+
public function it_retrieves_an_item_by_zero_index()
27+
{
28+
$data = new Collection([1, 2, 3]);
29+
30+
$this->assertEquals(1, $data->at(0));
31+
}
32+
}

0 commit comments

Comments
 (0)