Skip to content

Commit

Permalink
Iterators: add ReverseArray
Browse files Browse the repository at this point in the history
  • Loading branch information
h4kuna committed Nov 7, 2023
1 parent 3ba2a40 commit 75e70c1
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Iterators/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,20 @@ $wait = new ActiveWait(0.3); // wait 0.3s = 300ms

$wait->run(fn(): bool => random_int(1, 5) === 4);
```

# ReverseArray

Run array from end to begin.

```php
use h4kuna\DataType\Iterators\ReverseArray;

$iterator = new ReverseArray([1, 2, 3]);

foreach ($iterator as $item) {
echo $item;
}
// 3
// 2
// 1
```
49 changes: 49 additions & 0 deletions src/Iterators/ReverseArray.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php declare(strict_types=1);

namespace h4kuna\DataType\Iterators;

use Iterator;

/**
* @implements Iterator<mixed, mixed>
*/
final class ReverseArray implements Iterator
{
/**
* @param array<mixed, mixed> $array
*/
public function __construct(private array $array)
{
}


public function current(): mixed
{
return current($this->array);
}


public function next(): void
{
prev($this->array);
}


public function key(): mixed
{
return key($this->array);
}


public function valid(): bool
{
return key($this->array) !== null;
}


public function rewind(): void
{
end($this->array);
}

}
49 changes: 49 additions & 0 deletions tests/src/Unit/Iterators/ReverseArrayTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php declare(strict_types=1);

namespace h4kuna\DataType\Tests\Unit\Iterators;

use h4kuna\DataType\Iterators\ReverseArray;
use Tester\Assert;
use Tester\TestCase;

require_once __DIR__ . '/bootstrap.php';

/**
* @testCase
*/
final class ReverseArrayTest extends TestCase
{
/**
* @return array<mixed>
*/
protected function basicProvider(): array
{
return [
[
[1, 2, 3],
[2 => 3, 1 => 2, 0 => 1],
],
[
[],
[],
],
];
}


/**
* @dataProvider basicProvider
* @param array<mixed> $source
* @param array<mixed> $expected
*/
public function testBasic(array $source, array $expected): void
{
$actual = [];
foreach (new ReverseArray($source) as $k => $v) {
$actual[$k] = $v;
}
Assert::same($expected, $actual);
}
}

(new ReverseArrayTest())->run();

0 comments on commit 75e70c1

Please sign in to comment.