From 2ad4f7f462f88b52032bf6d746da077ae45c7e0a Mon Sep 17 00:00:00 2001 From: Jan Kramer Date: Thu, 9 Aug 2018 08:34:47 +0200 Subject: [PATCH] Add head function --- src/iter.php | 15 +++++++++++++++ test/iterTest.php | 15 +++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/iter.php b/src/iter.php index 5b609e9..4b1db7a 100644 --- a/src/iter.php +++ b/src/iter.php @@ -735,6 +735,21 @@ function dropWhile(callable $predicate, iterable $iterable): \Iterator { } } +/** + * Takes a non-empty iterable and returns the first element. + * + * @param iterable $iterable + * @return mixed + * @throws \InvalidArgumentException if argument is empty + */ +function head(iterable $iterable) { + foreach ($iterable as $value) { + return $value; + } + + throw new \InvalidArgumentException('Argument must be non-empty'); +} + /** * Takes an iterable containing any amount of nested iterables and returns * a flat iterable with just the values. diff --git a/test/iterTest.php b/test/iterTest.php index e8311dc..d886169 100644 --- a/test/iterTest.php +++ b/test/iterTest.php @@ -272,6 +272,21 @@ public function testTakeOrDropWhile() { ); } + public function testHead() + { + $this->assertSame(1, head([1,2,3])); + $this->assertSame(4, head(range(4,8))); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Argument must be non-empty + */ + public function testHeadOnEmptyArgumentError() + { + head([]); + } + public function testFlatten() { $this->assertSame( [1, 2, 3, 4, 5],