# heap

A generic binary heap with O(log n) insert, pop, update, and delete. The ordering is controlled by a **comparator function** passed to the constructor — no subclassing required.

---

## Classes

### `Heap<T>`

```typescript
new Heap<T>(compare: (a: T, b: T) => number, items?: Iterable<T>)
```

- `compare(a, b) < 0` → `a` should be at the top (min-heap style).
- `compare(a, b) > 0` → `b` should be at the top.

Pass `(a, b) => a - b` for a **min-heap**, `(a, b) => b - a` for a **max-heap**.

#### Methods

| Method | Complexity | Description |
|--------|-----------|-------------|
| `insert(value)` | O(log n) | Add a value; returns a `HeapItemRef` handle |
| `peek()` | O(1) | Return the top value without removing it; throws `EmptyHeapError` if empty |
| `pop()` | O(log n) | Remove and return the top value; throws `EmptyHeapError` if empty |
| `update(ref, newValue)` | O(log n) | Change a value and re-heapify in the correct direction |
| `delete(ref)` | O(log n) | Remove an arbitrary element by its ref |
| `toSortedArray()` | O(n log n) | Return all values sorted; heap is left **unchanged** |
| `size` (getter) | O(1) | Number of elements currently in the heap |

---

### `HeapItemRef<T>`

Returned by `insert`. Holds a reference back into the heap so `update` and `delete` can locate the element in O(log n).

```typescript
ref.value  // current value of this item
```

---

### `EmptyHeapError`

Thrown by `peek` and `pop` when the heap is empty.

---

## Examples

```typescript
// Min-heap
const h = new Heap<number>((a, b) => a - b, [5, 3, 8, 1]);
h.peek();           // 1
h.pop();            // 1  (h.size === 3)
h.toSortedArray();  // [3, 5, 8]  (heap unchanged)

// Updateable ref
const ref = h.insert(10);
h.update(ref, 0);   // 10 → 0, bubbles to top
h.peek();           // 0

// Arbitrary delete
h.delete(ref);
```

```typescript
// Max-heap (no subclassing — just reverse the comparator)
const maxH = new Heap<number>((a, b) => b - a, [3, 1, 4, 1, 5]);
maxH.pop();  // 5
maxH.pop();  // 4
```
