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 all 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
32 changes: 32 additions & 0 deletions src/iter.php
Expand Up @@ -893,6 +893,38 @@ function join(string $separator, iterable $iterable): string {
return $str;
}

/**
* Splits a string by a separator
*
* Examples:
*
* iter\split(', ', 'a, b, c')
* => iter('a', 'b', 'c')
*
* @param string $separator Separator to use between elements
* @param string $data The string to split
*
* @return iterable
*/
function split(string $separator, string $data): iterable
{
if (\strlen($separator) === 0) {
throw new \InvalidArgumentException('Separator must be non-empty string');
}

return (function() use ($separator, $data) {
$offset = 0;
while (
$offset < \strlen($data)
&& 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
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);
split('', 'a');
}

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