krahets/hello-algo · error · Error

The Deque Is Empty.

Error message

The Deque Is Empty.

What it means

Thrown by the array-based deque's peekFirst when the deque is empty. peekFirst returns the front element without removing it; the guard prevents reading #nums[#front] on a deque with queSize 0. popFirst relies on peekFirst, so it propagates the same error.

Source

Thrown at ja/codes/javascript/chapter_stack_and_queue/array_deque.js:88

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

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

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

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

    /* 出力用の配列を返す */
    toArray() {
        // 有効長の範囲内のリスト要素のみを変換
        const res = [];
        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. Check deque.isEmpty() before peekFirst()/popFirst().
  2. Structure consumers as while (!deque.isEmpty()).
  3. Return a sentinel/null when empty instead of letting the error propagate.
  4. Verify queSize > 0 at the call site.

Example fix

// before
const front = deque.peekFirst();  // throws if empty

// after
const front = deque.isEmpty() ? null : deque.peekFirst();
Defensive patterns

Strategy: validation

Validate before calling

function safePeekFirst(deque) {
  return deque.isEmpty() ? null : deque.peekFirst();
}

Type guard

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

Try / catch

try {
  return deque.peekFirst();
} catch (e) {
  if (e instanceof Error && e.message === 'The Deque Is Empty.') return null;
  throw e;
}

Prevention

When it happens

Trigger: Calling peekFirst() or popFirst() on an empty deque; reading the front after draining all elements; calling before any push.

Common situations: Using the deque as a BFS worklist that empties; calling peek at the start of processing before any insert; mismatched push/pop counts.

Related errors


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