Skip to content

Commit

Permalink
feat(str-grapheme): add reverse() function (#239)
Browse files Browse the repository at this point in the history
  • Loading branch information
yivi authored Oct 18, 2021
1 parent 2f0dad8 commit 08a6730
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/component/str-grapheme.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
- [ends_with](./../../src/Psl/Str/Grapheme/ends_with.php#L17)
- [ends_with_ci](./../../src/Psl/Str/Grapheme/ends_with_ci.php#L17)
- [length](./../../src/Psl/Str/Grapheme/length.php#L19)
- [reverse](./../../src/Psl/Str/Grapheme/reverse.php#L15)
- [search](./../../src/Psl/Str/Grapheme/search.php#L24)
- [search_ci](./../../src/Psl/Str/Grapheme/search_ci.php#L24)
- [search_last](./../../src/Psl/Str/Grapheme/search_last.php#L25)
Expand Down
1 change: 1 addition & 0 deletions src/Psl/Internal/Loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ final class Loader
'Psl\Str\Grapheme\ends_with',
'Psl\Str\Grapheme\ends_with_ci',
'Psl\Str\Grapheme\length',
'Psl\Str\Grapheme\reverse',
'Psl\Str\Grapheme\search',
'Psl\Str\Grapheme\search_ci',
'Psl\Str\Grapheme\search_last',
Expand Down
25 changes: 25 additions & 0 deletions src/Psl/Str/Grapheme/reverse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

namespace Psl\Str\Grapheme;

/**
* Reverses the string.
*
* @pure
*
* @throws \Psl\Exception\InvariantViolationException If unable to convert $string to UTF-16,
* or split it into graphemes
*/
function reverse(string $string): string
{
$reversed = '';
$offset = length($string);

while ($offset-- > 0) {
$reversed .= slice($string, $offset, 1);
}

return $reversed;
}
41 changes: 41 additions & 0 deletions tests/unit/Str/Grapheme/ReverseTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace Psl\Tests\Unit\Str\Grapheme;

use PHPUnit\Framework\TestCase;
use Psl\Exception;
use Psl\Str\Byte;
use Psl\Str\Grapheme;

class ReverseTest extends TestCase
{
public function provideData(): array
{
return [
['Hello World 👩🏽‍❤️‍👨🏼', '👩🏽‍❤️‍👨🏼 dlroW olleH'],
['👩‍👩‍👦👩🏽‍❤️‍👨🏼👩🏽‍🏫', '👩🏽‍🏫👩🏽‍❤️‍👨🏼👩‍👩‍👦'],
['某物 🖖🏿', '🖖🏿 物某' ],
['👲🏻 что-то', 'от-отч 👲🏻'],
['🙂👨🏼‍🎤😟', '😟👨🏼‍🎤🙂'],
['مرحبا👲🏻👨🏼‍🎤', '👨🏼‍🎤👲🏻ابحرم'],
];
}

/**
* @dataProvider provideData
*/
public function testReverse(string $string, string $expected): void
{
static::assertSame(Grapheme\reverse($string), $expected);
}

public function testFailReverse(): void
{
$string = Byte\slice('🐶🐶🐶', 0, 5);

$this->expectException(Exception\InvariantViolationException::class);
Grapheme\reverse($string);
}
}

0 comments on commit 08a6730

Please sign in to comment.