Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/iter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions test/iterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about using

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Argument must be non-empty');

instead?

Also see https://thephp.cc/news/2016/02/questioning-phpunit-best-practices.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, but it would be inconsistent with the other test cases since they all use annotations. Personally I'd prefer consistency and address this issue separately.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

*/
public function testHeadOnEmptyArgumentError()
{
head([]);
}

public function testFlatten() {
$this->assertSame(
[1, 2, 3, 4, 5],
Expand Down