Skip to content

Commit

Permalink
If the data is being entered in priority order then prepend the new p…
Browse files Browse the repository at this point in the history
…riority to save having to sort later
  • Loading branch information
lucasnetau committed Jun 16, 2023
1 parent 58a0bff commit 10379cd
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/TimeOrderedArray.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
use function array_key_last;
use function current;
use function next;
use function count;
use function array_key_first;

/**
* Class TimeOrderedArray
Expand Down Expand Up @@ -100,8 +102,18 @@ public function insert($value, $priority) : void
{
$this->values[] = [];
$newIndex = array_key_last($this->values);
$this->priorities[$priority] = $newIndex;
$this->prioritiesUnsorted = true;
$orderedInsert = false;
if ($this->prioritiesUnsorted === false) {
$currentPriority = array_key_first($this->priorities);
if ($currentPriority === null || -1 === $this->compare($priority, $currentPriority)) {
$this->priorities = [$priority => $newIndex] + $this->priorities;
$orderedInsert = true;
}
}
if ($orderedInsert === false) {
$this->priorities[$priority] = $newIndex;
$this->prioritiesUnsorted = true;
}
if (null === $this->top || 1 === $this->compare($priority, $this->top)) {
$this->top = $priority;
}
Expand Down

0 comments on commit 10379cd

Please sign in to comment.