Browse Source

Implemented Collection::last()

Jose Lorenzo Rodriguez 11 years ago
parent
commit
a50ff282f9

+ 8 - 0
src/Collection/CollectionInterface.php

@@ -536,6 +536,14 @@ interface CollectionInterface extends Iterator, JsonSerializable
      * @return mixed The first value in the collection will be returned.
      */
     public function first();
+
+    /**
+     * Returns the last result in this collection
+     *
+     * @return mixed The first value in the collection will be returned.
+     */
+    public function last();
+
     /**
      * Returns a new collection as the result of concatenating the list of elements
      * in this collection with the passed list of elements

+ 15 - 0
src/Collection/CollectionTrait.php

@@ -323,6 +323,21 @@ trait CollectionTrait
      * {@inheritDoc}
      *
      */
+    public function last()
+    {
+        $iterator = $this->unwrap();
+        $count = $iterator instanceof Countable ?
+            count($iterator) :
+            iterator_count($iterator);
+        foreach ($this->take(1, $count - 1) as $last) {
+            return $last;
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     *
+     */
     public function append($items)
     {
         $list = new AppendIterator;

+ 16 - 0
tests/TestCase/Collection/CollectionTest.php

@@ -1340,4 +1340,20 @@ class CollectionTest extends TestCase
 
         $this->assertEquals([5], $collection->skip(4)->toList());
     }
+
+    /**
+     * Tests the last() method
+     *
+     * @return void
+     */
+    public function testLast()
+    {
+        $collection = new Collection([1, 2, 3]);
+        $this->assertEquals(3, $collection->last());
+
+        $collection = $collection->map(function ($e) {
+            return $e * 2;
+        });
+        $this->assertEquals(6, $collection->last());
+    }
 }