{"record":{"id":"347c97d7c5f0f2ad","repo":"krahets/hello-algo","slug":"error-347c97","errorCode":null,"errorMessage":"佇列為空","messagePattern":"佇列為空","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"zh-hant/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js","lineNumber":57,"sourceCode":"        } else {\n            this.#rear.next = node;\n            this.#rear = node;\n        }\n        this.#queSize++;\n    }\n\n    /* 出列 */\n    pop() {\n        const num = this.peek();\n        // 刪除頭節點\n        this.#front = this.#front.next;\n        this.#queSize--;\n        return num;\n    }\n\n    /* 訪問佇列首元素 */\n    peek() {\n        if (this.size === 0) throw new Error('佇列為空');\n        return this.#front.val;\n    }\n\n    /* 將鏈結串列轉化為 Array 並返回 */\n    toArray() {\n        let node = this.#front;\n        const res = new Array(this.size);\n        for (let i = 0; i < res.length; i++) {\n            res[i] = node.val;\n            node = node.next;\n        }\n        return res;\n    }\n}\n\n/* Driver Code */\n/* 初始化佇列 */\nconst queue = new LinkedListQueue();","sourceCodeStart":39,"sourceCodeEnd":75,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/zh-hant/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js#L39-L75","documentation":"Thrown by LinkedListQueue.peek() (message: '佇列為空' = 'queue is empty') when size === 0. peek() dereferences front.val; without the guard it would throw a TypeError on null. pop() delegates to peek(), so dequeueing an empty queue surfaces this error.","triggerScenarios":"Calling pop() or peek() on a queue with no nodes, or dequeuing more items than enqueued.","commonSituations":"BFS exhaustion; producer/consumer mismatch; calling pop before any enqueue.","solutions":["Check queue.size > 0 (or a custom isEmpty) before pop() or peek().","Guard drain loops with while (queue.size > 0).","Initialize the queue and enqueue at least one element before peeking."],"exampleFix":"// before\nconst val = queue.pop(); // throws '佇列為空' (pop calls peek)\n\n// after\nwhile (queue.size > 0) {\n    const val = queue.pop();\n}","handlingStrategy":"validation","validationCode":"// peek() and pop() (which calls peek) both throw on empty\nif (queue.size > 0) {\n    const val = queue.pop();\n}","typeGuard":null,"tryCatchPattern":"try {\n    const val = queue.pop();\n} catch (e) {\n    if (e.message === '佇列為空') {\n        // queue is empty — handle underflow\n    } else throw e;\n}","preventionTips":["Check queue.size > 0 before pop() or peek().","Enqueue at least one element before peeking.","Guard BFS/consumer loops with while (queue.size > 0)."],"tags":["queue","linked-list","javascript","empty-state","precondition"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}