Skip to content

Commit a1b4a3e

Browse files
committed
feature: handled adding elements when queue is not empty
1 parent 1d1bddc commit a1b4a3e

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

round-linked-queue.js

+17-5
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,29 @@ class RoundLinkedQueue {
1818
}
1919

2020
get first() {
21-
return this._first;
21+
return this._first.data;
2222
}
2323

2424
get last() {
25-
return this._last;
25+
return this._last.data;
2626
}
2727

2828
add(element) {
29-
this._root = element;
30-
this._first = element;
31-
this._last = element;
29+
const node = {
30+
data: element,
31+
next: null,
32+
};
33+
34+
if (!this._root) {
35+
this._root = node;
36+
this._first = node;
37+
this._last = node;
38+
} else {
39+
const previousLast = this._last;
40+
previousLast.next = node;
41+
42+
this._last = node;
43+
}
3244

3345
this._length += 1;
3446
}

round-linked-queue.test.js

+17
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,22 @@ describe("Round-Queue", () => {
3737
// Length should've been increased by 1
3838
expect(queue.length).to.equal(originalLength + 1);
3939
});
40+
41+
it("Should add an element to the end of a non-empty queue", () => {
42+
const queue = new RoundQueue(3);
43+
const previousElement = 1;
44+
const elementToAdd = 2;
45+
// Make the queue non-empty
46+
queue.add(previousElement);
47+
48+
queue.add(elementToAdd);
49+
50+
// Element should've been added to the end of the queue
51+
expect(queue.last).to.equal(elementToAdd, "last not properly set");
52+
// But the first pointer must remain the first element added
53+
expect(queue.first).to.equal(previousElement, "first not properly set");
54+
// Length should've been increased by 2
55+
expect(queue.length).to.equal(2, "length not properly set");
56+
});
4057
});
4158
});

0 commit comments

Comments
 (0)