From 8dc4cfa293e1435354b0ca803cc5d956cfc01080 Mon Sep 17 00:00:00 2001 From: Bilge Date: Sat, 17 May 2025 12:17:02 +0100 Subject: [PATCH 1/2] Added \iter\last(). --- src/iter.php | 13 +++++++++++++ test/iterTest.php | 5 +++++ 2 files changed, 18 insertions(+) diff --git a/src/iter.php b/src/iter.php index 0d487b4..903b4e5 100644 --- a/src/iter.php +++ b/src/iter.php @@ -1290,6 +1290,19 @@ function tap(callable $function, iterable $iterable): \Iterator { } } +/** + * Returns the last value of the specified iterable. + * + * @param iterable $iterable Iterable. + * + * @return mixed Last value of the iterable if it contains values, otherwise null. + */ +function last(iterable $iterable): mixed { + foreach ($iterable as $value) {} + + return $value ?? null; +} + /* * Python: * compress() diff --git a/test/iterTest.php b/test/iterTest.php index 9b79854..453830d 100644 --- a/test/iterTest.php +++ b/test/iterTest.php @@ -644,6 +644,11 @@ public function testTap() { toArray(tap([$mock, 'foo'], [1, 2, 3])) ); } + + public function testLast() { + self::assertSame(3, last(range(1, 3))); + self::assertNull(last(new \EmptyIterator())); + } } class _CountableTestDummy implements \Countable { From c157509bd6d50116b703d41c64016f0780cae6f4 Mon Sep 17 00:00:00 2001 From: Bilge Date: Sun, 8 Jun 2025 22:28:39 +0100 Subject: [PATCH 2/2] Added array optimization to last(). Fixed PHP 7 compatibility. --- src/iter.php | 12 +++++++++--- test/iterTest.php | 7 ++++++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/iter.php b/src/iter.php index 903b4e5..2e0e672 100644 --- a/src/iter.php +++ b/src/iter.php @@ -1293,11 +1293,17 @@ function tap(callable $function, iterable $iterable): \Iterator { /** * Returns the last value of the specified iterable. * - * @param iterable $iterable Iterable. + * @template T + * + * @param iterable $iterable Iterable. * - * @return mixed Last value of the iterable if it contains values, otherwise null. + * @return T|null Last value of the iterable if it contains values, otherwise null. */ -function last(iterable $iterable): mixed { +function last(iterable $iterable) { + if (is_array($iterable)) { + return count($iterable) ? end($iterable) : null; + } + foreach ($iterable as $value) {} return $value ?? null; diff --git a/test/iterTest.php b/test/iterTest.php index 453830d..b6fc71f 100644 --- a/test/iterTest.php +++ b/test/iterTest.php @@ -646,8 +646,13 @@ public function testTap() { } public function testLast() { - self::assertSame(3, last(range(1, 3))); + self::assertSame(5, last((function () { + yield from range(1, 5); + })())); self::assertNull(last(new \EmptyIterator())); + + self::assertSame(3, last(range(1, 3))); + self::assertNull(last([])); } }