Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Implemented split #66 #80

Merged
merged 8 commits into from
Jun 8, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/iter.php
Original file line number Diff line number Diff line change
Expand Up @@ -893,6 +893,36 @@ function join(string $separator, iterable $iterable): string {
return $str;
}

/**
* Splits a string by a separator
*
* Examples:
*
* iter\split(', ', 'a, b, c')
* => iterable with values 'a', 'b' and 'c'
SamMousa marked this conversation as resolved.
Show resolved Hide resolved
*
* @param string $separator Separator to use between elements
* @param string $data The iterable to join
SamMousa marked this conversation as resolved.
Show resolved Hide resolved
*
* @return iterable
*/
function split(string $separator, string $data): iterable
{
if (strlen($separator) === 0) {
throw new \InvalidArgumentException('Separator must be non-empty string');
}

$offset = 0;
while (
$offset < strlen($data)
SamMousa marked this conversation as resolved.
Show resolved Hide resolved
&& false !== $nextOffset = strpos($data, $separator, $offset)
) {
yield substr($data, $offset, $nextOffset - $offset);
$offset = $nextOffset + strlen($separator);
}
yield substr($data, $offset);
}

/**
* Returns the number of elements an iterable contains.
*
Expand Down
12 changes: 12 additions & 0 deletions test/iterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,18 @@ public function testJoin() {
);
}

public function testSplit() {
$this->assertSame(['a', 'b', 'c'], toArray(split(', ', 'a, b, c')));
$this->assertSame(['b', 'b', 'b', 'b', 'b', 'b', 'b'], toArray(split('a', 'babababababab')));
nikic marked this conversation as resolved.
Show resolved Hide resolved

$this->assertSame(['a', 'b', '', '', 'c'], toArray(split(',', 'a,b,,,c')));
$this->assertSame(['', '', 'c'], toArray(split(',', ',,c')));
$this->assertSame(['c', '', ''], toArray(split(',', 'c,,')));

$this->expectException(\InvalidArgumentException::class);
toArray(split('', 'a'));
}

public function testChunk() {
$iterable = new \ArrayIterator(
['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]
Expand Down