krahets/hello-algo · error · Error

The Deque Is Empty.

Error message

The Deque Is Empty.

What it means

Thrown by peekFirst() on the array-backed deque when `isEmpty()` is true (queSize === 0). It is a plain Error guarding direct front access; peekFirst is also called internally by popFirst, so the same throw surfaces from popFirst on an empty deque.

Source

Thrown at ja/codes/typescript/chapter_stack_and_queue/array_deque.ts:88

    /* キュー先頭からデキュー */
    popFirst(): number {
        const num: number = this.peekFirst();
        // 先頭ポインタを 1 つ後ろへ進める
        this.front = this.index(this.front + 1);
        this.queSize--;
        return num;
    }

    /* キュー末尾からデキュー */
    popLast(): number {
        const num: number = this.peekLast();
        this.queSize--;
        return num;
    }

    /* キュー先頭の要素にアクセス */
    peekFirst(): number {
        if (this.isEmpty()) throw new Error('The Deque Is Empty.');
        return this.nums[this.front];
    }

    /* キュー末尾の要素にアクセス */
    peekLast(): number {
        if (this.isEmpty()) throw new Error('The Deque Is Empty.');
        // 末尾要素のインデックスを計算
        const last = this.index(this.front + this.queSize - 1);
        return this.nums[last];
    }

    /* 出力用の配列を返す */
    toArray(): number[] {
        // 有効長の範囲内のリスト要素のみを変換
        const res: number[] = [];
        for (let i = 0, j = this.front; i < this.queSize; i++, j++) {
            res[i] = this.nums[this.index(j)];
        }

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard with `if (!deque.isEmpty())` before peekFirst/popFirst.
  2. Loop with `while (!deque.isEmpty())` when draining.
  3. Wrap in try/catch if an empty deque is an expected, recoverable state.

Example fix

// before
const head = deque.peekFirst();

// after
const head = deque.isEmpty() ? undefined : deque.peekFirst();
Defensive patterns

Strategy: validation

Validate before calling

// Guard front access on the deque.
if (!deque.isEmpty()) {
  const head = deque.peekFirst();
}

Type guard

function dequeCanPeek(deque) {
  return !deque.isEmpty();
}

Try / catch

try {
  const head = deque.peekFirst();
} catch (e) {
  if (e instanceof Error && /Deque Is Empty/.test(e.message)) {
    // empty — handle gracefully
  } else throw e;
}

Prevention

When it happens

Trigger: Calling peekFirst() (or popFirst, which delegates to peekFirst) on a deque with queSize 0; dequeuing more than was enqueued; peeking after a clear/reset without re-checking size.

Common situations: Processing a queue that drained faster than it filled; using peekFirst as a non-failing check (it throws, it does not return undefined); off-by-one in a producer/consumer that over-consumes one element.

Related errors


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