krahets/hello-algo · error · Error

キューが空です

Error message

キューが空です

What it means

Thrown by the array-based circular queue's peek when the queue is empty. peek returns the element at the front pointer; the guard prevents reading stale data when queSize is 0. pop() calls peek() first, so dequeue on an empty queue surfaces this same error.

Source

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

        // 剰余演算により、rear が配列末尾を越えた後に先頭へ戻るようにする
        const rear = (this.#front + this.size) % this.capacity;
        // num をキュー末尾に追加
        this.#nums[rear] = num;
        this.#queSize++;
    }

    /* デキュー */
    pop() {
        const num = this.peek();
        // 先頭ポインタを1つ後ろへ進め、末尾を越えたら配列先頭に戻す
        this.#front = (this.#front + 1) % this.capacity;
        this.#queSize--;
        return num;
    }

    /* キュー先頭の要素にアクセス */
    peek() {
        if (this.isEmpty()) throw new Error('キューが空です');
        return this.#nums[this.#front];
    }

    /* Array を返す */
    toArray() {
        // 有効長の範囲内のリスト要素のみを変換
        const arr = new Array(this.size);
        for (let i = 0, j = this.#front; i < this.size; i++, j++) {
            arr[i] = this.#nums[j % this.capacity];
        }
        return arr;
    }
}

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

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check queue.isEmpty() (or queue.size() === 0) before peek()/pop().
  2. Use while (!queue.isEmpty()) for processing loops.
  3. Return a sentinel when empty if a missing element is not an error.
  4. Validate the enqueue/dequeue pairing in your logic.

Example fix

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

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

Strategy: validation

Validate before calling

function safePeek(queue) {
  return queue.isEmpty() ? null : queue.peek();
}

Type guard

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

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; dequeuing more items than were enqueued; calling at startup before any enqueue.

Common situations: BFS/level-order traversal where the queue legitimately drains; producer-consumer mismatch; calling pop in a loop with a wrong termination condition.

Related errors


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