Skip to content

Commit

Permalink
Add last key and last item
Browse files Browse the repository at this point in the history
  • Loading branch information
jfilla committed Nov 1, 2019
1 parent bc43019 commit 2d12417
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/Utils/Arrays.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ function (array $item) use ($key) {

/**
* @param iterable<mixed> $collection
* @return mixed|null
* @return mixed
*/
public static function firstItem(iterable $collection)
{
Expand All @@ -168,6 +168,25 @@ public static function firstKey(iterable $collection)
return $key;
}

/**
* @param iterable<mixed> $collection
* @return mixed
*/
public static function lastItem(iterable $collection)
{
return $collection[self::lastKey($collection)] ?? null;
}

/**
* @param iterable<mixed> $collection
* @return mixed
*/
public static function lastKey(iterable $collection)
{
end($collection);
return key($collection);
}

/**
* @param array<mixed> $array
* @param string $prefix
Expand Down Expand Up @@ -598,4 +617,5 @@ private static function trimValue($value)
{
return is_string($value) ? trim($value) : $value;
}

}
11 changes: 11 additions & 0 deletions tests/UtilsTests/ArraysTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,16 @@ public function testFirstKey(): void
$this->assertEquals('some-key', Arrays::firstKey(['some-key' => 'some-value', 2 => 'two']));
}

public function testLastItem(): void
{
$this->assertEquals(1, Arrays::lastItem([2, 1]));
}

public function testLastKey(): void
{
$this->assertEquals(2, Arrays::lastKey([1 => 1, 2 => 2]));
}

public function testFlattenKeys(): void
{
$this->assertEquals(
Expand Down Expand Up @@ -500,4 +510,5 @@ function ($a) {
)
);
}

}

0 comments on commit 2d12417

Please sign in to comment.