krahets/hello-algo · error · Error

The Deque Is Empty.

Error message

The Deque Is Empty.

What it means

Thrown by ArrayDeque.peekFirst() (message: 'The Deque Is Empty.') when the deque has no elements. The method accesses nums[front]; without the guard it would return undefined, masking a logic error.

Source

Thrown at zh-hant/codes/javascript/chapter_stack_and_queue/array_deque.js:88

    /* 佇列首出列 */
    popFirst() {
        const num = this.peekFirst();
        // 佇列首指標向後移動一位
        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. Call deque.isEmpty() (or check size > 0) before peekFirst().
  2. Guard consumer loops with while (deque.size() > 0).
  3. Return a default value or sentinel when the deque is empty instead of peeking.

Example fix

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

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

Strategy: validation

Validate before calling

if (!deque.isEmpty()) {
    const head = deque.peekFirst();
}

Try / catch

try {
    const head = deque.peekFirst();
} catch (e) {
    if (e.message === 'The Deque Is Empty.') {
        // deque is empty — return null or default
    } else throw e;
}

Prevention

When it happens

Trigger: Calling peekFirst() on a newly constructed or fully drained deque.

Common situations: Peeking before any push/unshift; underflow after a pop/poll loop; using the deque as a sliding window without checking remaining size.

Related errors


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