Skip to content

Commit

Permalink
Reverse internal ordering of ItemList so that it can use O(1) array_p…
Browse files Browse the repository at this point in the history
…op rather than O(n) array_shift
  • Loading branch information
dvdoug committed Nov 12, 2018
1 parent ce3bfa0 commit 7c9e128
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/ItemList.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
use Countable;
use IteratorAggregate;
use Traversable;
use function array_shift;
use function array_pop;
use function array_reverse;
use function count;
use function reset;
use function end;
use function usort;

/**
Expand Down Expand Up @@ -87,7 +88,7 @@ public function extract(): Item
$this->isSorted = true;
}

return array_shift($this->list);
return array_pop($this->list);
}

/**
Expand All @@ -103,7 +104,7 @@ public function top(): Item
}
$temp = $this->list;

return reset($temp);
return end($temp);
}

/**
Expand All @@ -116,7 +117,7 @@ public function getIterator(): Traversable
$this->isSorted = true;
}

return new ArrayIterator($this->list);
return new ArrayIterator(array_reverse($this->list));
}

/**
Expand All @@ -139,14 +140,15 @@ private function compare(Item $itemA, Item $itemB): int
{
$itemAVolume = $itemA->getWidth() * $itemA->getLength() * $itemA->getDepth();
$itemBVolume = $itemB->getWidth() * $itemB->getLength() * $itemB->getDepth();
$volumeDecider = $itemBVolume <=> $itemAVolume;
$weightDecider = $itemB->getWeight() - $itemA->getWeight();
$volumeDecider = $itemAVolume <=> $itemBVolume;
$weightDecider = $itemA->getWeight() - $itemB->getWeight();
if ($volumeDecider !== 0) {
return $volumeDecider;
} elseif ($weightDecider !== 0) {
}
if ($weightDecider !== 0) {
return $weightDecider;
} else {
return $itemA->getDescription() <=> $itemB->getDescription();
}

return $itemB->getDescription() <=> $itemA->getDescription();
}
}

0 comments on commit 7c9e128

Please sign in to comment.