Skip to content

Core\Heap::peek

$heap->peek(): T

Returns the smallest value in a heap and leaves it in the heap.

peek gives the same value that pop would give next, but the heap does not change. Use it when you want to decide something before you take the value out, for example whether the next job is due yet. "Smallest" means the order the heap uses: its comparator function, the compareTo method of its objects, or the normal order of numbers and strings.

Good to know: peek on an empty heap throws a RuntimeError. It does not return null. Call isEmpty first when the heap can be empty.

Return value

Returns T. The first element. The heap does not change.

Errors

  • RuntimeErrorThe heap is empty. Call isEmpty first to check.

Examples

Look without taking

<?nvs
// Shows how to read the smallest value of a heap without removing it.
var $heap = new Core\Heap<int>();
$heap->push(7);
$heap->push(3);
$heap->push(9);
// This prints 3.
echo $heap->peek(), "\n";
// The heap still has all three values. This prints the count, 3.
echo $heap->count(), "\n";
Output
3
3

An empty heap

<?nvs
// Shows what happens when you call `peek` on a heap with no values.
var $heap = new Core\Heap<int>();
// `isEmpty` is the check to make first. This prints "Nothing to read".
if ($heap->isEmpty()) {
echo "Nothing to read\n";
}
// Without that check, `peek` throws a `RuntimeError`. This prints "peek threw an error".
try {
echo $heap->peek(), "\n";
} catch (RuntimeError $error) {
echo "peek threw an error\n";
}
Output
Nothing to read
peek threw an error

Run the jobs that are due

<?nvs
// Shows a small scheduler. It runs only the jobs that are due now and keeps the others for later.
class Job implements Comparable
{
public string $name;
public int $minute;
public function constructor(string $name, int $minute)
{
$this->name = $name;
$this->minute = $minute;
}
// The job with the earliest minute comes first.
public function compareTo(Job $other): int
{
return $this->minute - $other->minute;
}
}
var $jobs = new Core\Heap<Job>();
$jobs->push(new Job('send the newsletter', 30));
$jobs->push(new Job('clean the cache', 5));
$jobs->push(new Job('write the daily report', 12));
int $now = 15;
// `peek` checks the next job without taking it. A job is taken only when it is due.
while (!$jobs->isEmpty() && $jobs->peek()->minute <= $now) {
echo 'running: ', $jobs->pop()->name, "\n";
}
// This prints 1, because one job is not due yet.
echo 'still waiting: ', $jobs->count(), "\n";
Output
running: clean the cache
running: write the daily report
still waiting: 1