{"record":{"id":"b55910c58bffb4ca","repo":"krahets/hello-algo","slug":"error-b55910","errorCode":null,"errorMessage":"队列为空","messagePattern":"队列为空","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"codes/typescript/chapter_stack_and_queue/array_queue.ts","lineNumber":58,"sourceCode":"        // 通过取余操作实现 rear 越过数组尾部后回到头部\n        const rear = (this.front + this.queSize) % this.capacity;\n        // 将 num 添加至队尾\n        this.nums[rear] = num;\n        this.queSize++;\n    }\n\n    /* 出队 */\n    pop(): number {\n        const num = this.peek();\n        // 队首指针向后移动一位，若越过尾部，则返回到数组头部\n        this.front = (this.front + 1) % this.capacity;\n        this.queSize--;\n        return num;\n    }\n\n    /* 访问队首元素 */\n    peek(): number {\n        if (this.isEmpty()) throw new Error('队列为空');\n        return this.nums[this.front];\n    }\n\n    /* 返回 Array */\n    toArray(): number[] {\n        // 仅转换有效长度范围内的列表元素\n        const arr = new Array(this.size);\n        for (let i = 0, j = this.front; i < this.size; i++, j++) {\n            arr[i] = this.nums[j % this.capacity];\n        }\n        return arr;\n    }\n}\n\n/* Driver Code */\n/* 初始化队列 */\nconst capacity = 10;\nconst queue = new ArrayQueue(capacity);","sourceCodeStart":40,"sourceCodeEnd":76,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/codes/typescript/chapter_stack_and_queue/array_queue.ts#L40-L76","documentation":"Thrown by ArrayQueue.peek() ('队列为空' / queue is empty) when queSize === 0. peek() returns nums[front]; on an empty queue front is stale, so the guard prevents returning undefined-as-number. pop() calls peek() first, so pop on an empty queue surfaces the same error.","triggerScenarios":"Calling pop() or peek() on an empty queue; a consumer loop that dequeues more items than were enqueued.","commonSituations":"Draining a queue without an isEmpty check; calling peek before any push; a worker that processes faster than the producer and hits an empty window.","solutions":["Guard with isEmpty(): if (!queue.isEmpty()) queue.pop().","Use while (!queue.isEmpty()) for drain loops.","Track enqueue/dequeue counts and never dequeue beyond the enqueued total."],"exampleFix":"// before\nconst head = queue.peek(); // throws when empty\n// after\nif (!queue.isEmpty()) {\n    const head = queue.peek();\n}","handlingStrategy":"validation","validationCode":"function safePeek(queue) {\n  return queue.isEmpty() ? undefined : queue.peek();\n}","typeGuard":"null","tryCatchPattern":"null","preventionTips":["Check queue.isEmpty() before peek/pop.","Use while (!queue.isEmpty()) for drain loops.","Track enqueue/dequeue counts; never dequeue past the total."],"tags":["typescript","queue","empty-state","validation"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}