krahets/hello-algo · error · Error

堆積為空

Error message

堆積為空

What it means

Thrown by MaxHeap.pop() (message: '堆積為空' = 'heap is empty') when isEmpty() is true. pop() swaps the root with the last leaf, removes it, then sifts down; without the guard it would return undefined and corrupt heap ordering.

Source

Thrown at zh-hant/codes/javascript/chapter_heap/my_heap.js:85

    /* 從節點 i 開始,從底至頂堆積化 */
    #siftUp(i) {
        while (true) {
            // 獲取節點 i 的父節點
            const p = this.#parent(i);
            // 當“越過根節點”或“節點無須修復”時,結束堆積化
            if (p < 0 || this.#maxHeap[i] <= this.#maxHeap[p]) break;
            // 交換兩節點
            this.#swap(i, p);
            // 迴圈向上堆積化
            i = p;
        }
    }

    /* 元素出堆積 */
    pop() {
        // 判空處理
        if (this.isEmpty()) throw new Error('堆積為空');
        // 交換根節點與最右葉節點(交換首元素與尾元素)
        this.#swap(0, this.size() - 1);
        // 刪除節點
        const val = this.#maxHeap.pop();
        // 從頂至底堆積化
        this.#siftDown(0);
        // 返回堆積頂元素
        return val;
    }

    /* 從節點 i 開始,從頂至底堆積化 */
    #siftDown(i) {
        while (true) {
            // 判斷節點 i, l, r 中值最大的節點,記為 ma
            const l = this.#left(i),
                r = this.#right(i);
            let ma = i;
            if (l < this.size() && this.#maxHeap[l] > this.#maxHeap[ma]) ma = l;

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check heap.isEmpty() before calling pop().
  2. If consuming in a loop, use while (!heap.isEmpty()) as the loop condition.
  3. Track element count externally if the heap is shared across producers/consumers.

Example fix

// before
const val = heap.pop(); // throws '堆積為空' if empty

// after
while (!heap.isEmpty()) {
    const val = heap.pop();
}
Defensive patterns

Strategy: validation

Validate before calling

if (!heap.isEmpty()) {
    const val = heap.pop();
}

Try / catch

try {
    const val = heap.pop();
} catch (e) {
    if (e.message === '堆積為空') {
        // heap is empty — handle underflow
    } else throw e;
}

Prevention

When it happens

Trigger: Calling pop() on a heap that has no elements, or calling pop() more times than elements were pushed.

Common situations: Draining a heap/priority queue in a loop without a termination check; heap-sort on an already-empty collection; underflow from concurrent consumers.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/6929d017cc45f10f. Report an issue: GitHub.