krahets/hello-algo · error · Error

キューが空です

Error message

キューが空です

What it means

Thrown by peek() on the array-backed queue when `isEmpty()` is true. Plain Error. pop() calls peek() internally first, so pop() on an empty queue propagates this exact throw before mutating front/queSize.

Source

Thrown at ja/codes/typescript/chapter_stack_and_queue/array_queue.ts:58

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

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

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

    /* Array を返す */
    toArray(): number[] {
        // 有効長の範囲内のリスト要素のみを変換
        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. Guard with `if (!queue.isEmpty())` or loop `while (!queue.isEmpty())`.
  2. Catch the Error if empty is a recoverable condition.
  3. Audit loop bounds so you never pop more than `queue.size()` times.

Example fix

// before
const head = queue.peek();

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

Strategy: validation

Validate before calling

// Guard queue access.
if (!queue.isEmpty()) {
  const head = queue.peek();
}

Type guard

function queueCanPeek(queue) {
  return !queue.isEmpty();
}

Try / catch

try {
  const head = queue.peek();
} catch (e) {
  if (e instanceof Error && e.message === 'キューが空です') {
    // empty queue
  } else throw e;
}

Prevention

When it happens

Trigger: Calling peek() or pop() (delegates to peek) when queSize is 0; consuming from a queue that has been fully drained; calling pop after a reset without re-checking size.

Common situations: BFS-style loops that pop one extra element; producer-consumer where the consumer outpaces the producer; assuming peek returns undefined on empty.

Related errors


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