Skip to content

Instantly share code, notes, and snippets.

@enumag
Created November 29, 2018 12:11
Show Gist options
  • Save enumag/21c5a266b48bbc9fe8c1c5f6f6300a3a to your computer and use it in GitHub Desktop.
Save enumag/21c5a266b48bbc9fe8c1c5f6f6300a3a to your computer and use it in GitHub Desktop.
OrderedCollection
<?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