Skip to content

Commit afd1238

Browse files
authored
bug #30 Keep FIFO order in PriorityQueue (pamil)
This PR was merged into the 1.7-dev branch. Discussion ---------- Sorts them first by priority descending, then by the order in which they were added ascending. Commits ------- c1f2558 Keep FIFO order in PriorityQueue
2 parents edde22a + c1f2558 commit afd1238

File tree

2 files changed

+15
-17
lines changed

2 files changed

+15
-17
lines changed

spec/Suite/PriorityQueueSpec.php

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,20 @@ function it_is_initializable(): void
2525

2626
function it_keeps_fifo_order_for_elements_with_same_priority(): void
2727
{
28-
$this->insert(['element' => 1]);
2928
$this->insert(['element' => 2]);
29+
$this->insert(['element' => 1]);
30+
$this->insert(['element' => 3]);
3031

31-
$this->getIterator()->shouldIterateAs([['element' => 1], ['element' => 2]]);
32+
$this->getIterator()->shouldIterateAs([['element' => 2], ['element' => 1], ['element' => 3]]);
3233
}
3334

3435
function it_sorts_elements_by_their_priority(): void
3536
{
36-
$this->insert(['element' => 3], -1);
37+
$this->insert(['element' => 1], -1);
3738
$this->insert(['element' => 2], 0);
38-
$this->insert(['element' => 1], 1);
39+
$this->insert(['element' => 3], 1);
40+
$this->insert(['element' => 4], 0);
3941

40-
$this->getIterator()->shouldIterateAs([['element' => 1], ['element' => 2], ['element' => 3]]);
42+
$this->getIterator()->shouldIterateAs([['element' => 3], ['element' => 2], ['element' => 4], ['element' => 1]]);
4143
}
4244
}

src/Suite/PriorityQueue.php

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,6 @@ final class PriorityQueue implements \IteratorAggregate
2525
*/
2626
private $records = [];
2727

28-
/**
29-
* @psalm-var array<int, array>
30-
*
31-
* @var array[]
32-
*/
33-
private $sortedRecords = [];
34-
3528
/** @var bool */
3629
private $sorted = false;
3730

@@ -44,16 +37,19 @@ public function insert(array $data, int $priority = 0): void
4437
public function getIterator(): \Traversable
4538
{
4639
if ($this->sorted === false) {
47-
// Reversing the records to maintain FIFO order for item with the same priority
48-
$this->sortedRecords = array_reverse($this->records);
49-
5040
/** @psalm-suppress InvalidPassByReference Doing PHP magic, it works this way */
51-
array_multisort(array_column($this->sortedRecords, 'priority'), \SORT_DESC, $this->sortedRecords);
41+
array_multisort(
42+
array_column($this->records, 'priority'),
43+
\SORT_DESC,
44+
array_keys($this->records),
45+
\SORT_ASC,
46+
$this->records
47+
);
5248

5349
$this->sorted = true;
5450
}
5551

56-
foreach ($this->sortedRecords as $record) {
52+
foreach ($this->records as $record) {
5753
yield $record['data'];
5854
}
5955
}

0 commit comments

Comments
 (0)