krahets/hello-algo · error · Error

キューが空

Error message

キューが空

What it means

Thrown by the linked-list queue's peek when the queue is empty (size === 0). peek reads this.#front.val; without the guard, #front would be null and reading .val would throw a TypeError instead. pop() calls peek() first, so dequeue on an empty queue yields this controlled error.

Source

Thrown at ja/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js:57

        } else {
            this.#rear.next = node;
            this.#rear = node;
        }
        this.#queSize++;
    }

    /* デキュー */
    pop() {
        const num = this.peek();
        // 先頭ノードを削除
        this.#front = this.#front.next;
        this.#queSize--;
        return num;
    }

    /* キュー先頭の要素にアクセス */
    peek() {
        if (this.size === 0) throw new Error('キューが空');
        return this.#front.val;
    }

    /* 連結リストを Array に変換して返す */
    toArray() {
        let node = this.#front;
        const res = new Array(this.size);
        for (let i = 0; i < res.length; i++) {
            res[i] = node.val;
            node = node.next;
        }
        return res;
    }
}

/* Driver Code */
/* キューを初期化 */
const queue = new LinkedListQueue();

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check queue.size() === 0 (or an isEmpty) before peek()/pop().
  2. Use while (queue.size() > 0) for drain loops.
  3. Return a sentinel when the queue is empty.
  4. Ensure enqueue/dequeue calls are balanced.

Example fix

// before
const head = queue.peek();  // throws if empty

// after
const head = queue.size === 0 ? null : queue.peek();
Defensive patterns

Strategy: validation

Validate before calling

function safePeek(queue) {
  return queue.size === 0 ? null : queue.peek();
}

Type guard

const isNonEmpty = (q) => typeof q.size === 'number' && q.size > 0;

Try / catch

try {
  return queue.peek();
} catch (e) {
  if (e instanceof Error && e.message === 'キューが空') return null;
  throw e;
}

Prevention

When it happens

Trigger: Calling peek() or pop() on an empty queue (no enqueues, or all dequeued); calling after the front/rear pointers have returned to their initial empty state.

Common situations: BFS where the queue drains; producer-consumer imbalance; calling peek at the start of a function before any enqueue.

Related errors


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