Skip to content

Commit

Permalink
Allow to use objects as map keys (#105)
Browse files Browse the repository at this point in the history
* Allow to use objects as map keys

* add more tests

* allow cast map to native array
  • Loading branch information
akondas authored May 30, 2024
1 parent 046887b commit e9173fa
Show file tree
Hide file tree
Showing 4 changed files with 209 additions and 69 deletions.
27 changes: 21 additions & 6 deletions src/Collection/Iterator/MapIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,22 @@

use Munus\Collection\Iterator;
use Munus\Exception\NoSuchElementException;
use Munus\Tuple;
use Munus\Tuple\Tuple2;

/**
* @template K
* @template V
*/
final class MapIterator extends Iterator
{
/**
* @var mixed[]
* @var array<Tuple2<K,V>>
*/
private array $map;

/**
* @param array<Tuple2<K,V>> $map
*/
public function __construct(array $map)
{
$this->map = $map;
Expand All @@ -23,25 +30,30 @@ public function __construct(array $map)

public function key(): mixed
{
return key($this->map);
return current($this->map)[0];
}

public function current(): mixed
{
return current($this->map);
return current($this->map)[1];
}

public function rewind(): void
{
reset($this->map);
}

public function next(): Tuple
/**
* @throws NoSuchElementException
*
* @return Tuple2<K, V>
*/
public function next(): Tuple2
{
if (!$this->valid()) {
throw new NoSuchElementException();
}
$next = Tuple::of(key($this->map), current($this->map));
$next = current($this->map);
next($this->map);

return $next;
Expand All @@ -57,6 +69,9 @@ public function hasNext(): bool
return $this->valid();
}

/**
* @return array<Tuple2<K, V>>
*/
public function toArray(): array
{
return $this->map;
Expand Down
Loading

0 comments on commit e9173fa

Please sign in to comment.