Skip to content

Commit f4f8c9a

Browse files
committed
feature: handled removing an element from an empty queue
1 parent e87c311 commit f4f8c9a

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

round-linked-queue.js

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ class RoundLinkedQueue {
3030
next: null,
3131
};
3232

33-
let removedElement;
33+
let removedNode = {};
3434

3535
if (this.length < this.maxLength) {
3636
if (!this._first) {
@@ -40,23 +40,26 @@ class RoundLinkedQueue {
4040

4141
this._length += 1;
4242
} else {
43-
removedElement = this._first.data;
43+
removedNode = this._first;
4444
this._first = this._first.next;
4545
}
4646

4747
this._last.next = node;
4848
this._last = node;
4949

50-
return removedElement;
50+
return removedNode.data;
5151
}
5252

5353
remove() {
54-
const removedElement = this.first;
54+
const removedNode = this._first;
55+
if (!removedNode) {
56+
throw new Error("Cannot remove element from an empty queue");
57+
}
5558

5659
this._first = this._first.next;
5760
this._length -= 1;
5861

59-
return removedElement;
62+
return removedNode.data;
6063
}
6164
}
6265

round-linked-queue.test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,5 +108,11 @@ describe("Round-Queue", () => {
108108
expect(queue.first).to.equal(2, "should shift the second element to the head of the queue");
109109
expect(queue.last).to.equal(3, "should not change the last element");
110110
});
111+
112+
it("Should throw an error when the queue is empty", () => {
113+
const queue = new RoundQueue(3);
114+
115+
expect(() => queue.remove()).to.throw("Cannot remove element from an empty queue");
116+
});
111117
});
112118
});

0 commit comments

Comments
 (0)