Created
November 29, 2018 12:11
-
-
Save enumag/21c5a266b48bbc9fe8c1c5f6f6300a3a to your computer and use it in GitHub Desktop.
OrderedCollection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
namespace App\Library\DataStructures; | |
use Ds\Vector; | |
use Iterator; | |
use IteratorAggregate; | |
final class OrderedCollection implements IteratorAggregate | |
{ | |
/** | |
* @var bool | |
*/ | |
private $isOrdered = true; | |
/** | |
* @var Vector | |
*/ | |
private $items; | |
/** | |
* @var callable | |
*/ | |
private $comparator; | |
public function __construct(callable $comparator) | |
{ | |
$this->comparator = $comparator; | |
$this->items = new Vector(); | |
} | |
public function push($item): void | |
{ | |
$this->items->push($item); | |
$this->isOrdered = false; | |
} | |
public function getIterator(): Iterator | |
{ | |
if (! $this->isOrdered) { | |
$this->items->sort($this->comparator); | |
$this->isOrdered = true; | |
} | |
yield from clone $this->items; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment