krahets/hello-algo · error · Error

ヒープが空です

Error message

ヒープが空です

What it means

Thrown by the max-heap's pop method when the heap is empty (isEmpty() returns true). The guard prevents swapping/reading the root of a zero-length internal array and returning an undefined value. The heap is a max-heap, so pop returns and removes the largest element.

Source

Thrown at ja/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;
            // 2 つのノードを交換
            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() (or heap.size() > 0) before every pop().
  2. Use a while (!heap.isEmpty()) loop when draining the heap.
  3. If pop is optional, skip it when empty rather than throwing.
  4. Wrap in try/catch only when emptiness is genuinely unexpected.

Example fix

// before
const max = heap.pop();  // throws if empty

// after
const max = heap.isEmpty() ? null : heap.pop();
Defensive patterns

Strategy: validation

Validate before calling

function safePop(heap) {
  return heap.isEmpty() ? null : heap.pop();
}

Type guard

const isNonEmpty = (heap) => typeof heap.isEmpty === 'function' && !heap.isEmpty();

Try / catch

try {
  return heap.pop();
} catch (e) {
  if (e instanceof Error && e.message === 'ヒープが空です') return null;
  throw e;
}

Prevention

When it happens

Trigger: Calling pop() on a freshly constructed heap with no elements inserted; calling pop() more times than the number of push() calls; draining the heap in a loop without an empty check.

Common situations: Processing a priority queue that legitimately empties; calling pop() after clear/reset; loop conditions that assume at least one element remains.

Related errors


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