krahets/hello-algo · error · Error
佇列為空
Error message
佇列為空
What it means
Thrown by ArrayQueue.peek() (message: '佇列為空' = 'queue is empty') when the queue has no elements. peek() returns nums[front]; without the guard it returns stale/undefined data. pop() delegates to peek(), so pop on an empty queue also triggers this.
Source
Thrown at zh-hant/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();
// 佇列首指標向後移動一位,若越過尾部,則返回到陣列頭部
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
- Check queue.isEmpty() before pop() or peek().
- Use while (queue.size > 0) for drain loops.
- If peeking for display, guard with isEmpty() and return null or a placeholder.
Example fix
// before
const val = queue.pop(); // throws '佇列為空' if empty (pop calls peek)
// after
while (queue.size > 0) {
const val = queue.pop();
} Defensive patterns
Strategy: validation
Validate before calling
// peek() and pop() (which calls peek) both throw on empty
if (queue.size > 0) {
const val = queue.pop();
} Try / catch
try {
const val = queue.pop();
} catch (e) {
if (e.message === '佇列為空') {
// queue is empty — handle underflow
} else throw e;
} Prevention
- Check queue.size > 0 before pop() or peek().
- Use while (queue.size > 0) for drain loops.
- Remember pop() internally calls peek(), so both need the guard.
When it happens
Trigger: Calling pop() or peek() on an empty queue, or dequeuing more items than were enqueued.
Common situations: Consumer loop draining faster than producer; FIFO processing with no guard; stale front pointer after capacity reset.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/90110a30739f00b0.
Report an issue: GitHub.