Skip to content

Commit bdad8db

Browse files
committedDec 29, 2018
--update: added code for Weaving 2 queues
1 parent d220bf6 commit bdad8db

File tree

4 files changed

+69
-2
lines changed

4 files changed

+69
-2
lines changed
 

‎src/_DataStructures_/Queue/Queue.test.js

+18-2
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,35 @@ describe('Data Structure : Queue', () => {
1212
queue = new Queue();
1313
});
1414

15-
it('Should add element to a queue', () => {
15+
it('Should add() element to a queue', () => {
1616
queue.add(5);
1717
expect(queue.data).toEqual([5]);
1818
});
1919

20-
it('Should remove an element from the queue', () => {
20+
it('Should remove() an element from the queue', () => {
2121
queue.add(2);
2222
queue.add(3);
2323
queue.remove();
2424

2525
expect(queue.data).toEqual([3]);
2626
});
2727

28+
describe('peek()', () => {
29+
beforeEach(() => {
30+
queue.add(2);
31+
queue.add(5);
32+
});
33+
34+
it('Should return the elemet to be removed using peek()', () => {
35+
expect(queue.peek()).toEqual(2);
36+
});
37+
38+
it('Should not remove the element', () => {
39+
expect(queue.peek()).toEqual(2);
40+
expect(queue.remove()).toEqual(2);
41+
});
42+
});
43+
2844
it('Should maintain the order of elements', () => {
2945
// first in first out
3046
queue.add(2);

‎src/_DataStructures_/Queue/index.js

+4
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ class Queue {
88
return this.data.unshift(element);
99
}
1010

11+
peek() {
12+
return this.data[this.data.length - 1];
13+
}
14+
1115
remove() {
1216
return this.data.pop();
1317
}
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const Queue = require('../index');
2+
3+
function weaveQueues(first, second) {
4+
const weaved = new Queue();
5+
6+
while (first.peek() || second.peek()) {
7+
if (first.peek() !== undefined) {
8+
weaved.add(first.remove());
9+
}
10+
11+
if (second.peek() !== undefined) {
12+
weaved.add(second.remove());
13+
}
14+
}
15+
return weaved;
16+
}
17+
18+
module.exports = {
19+
weaveQueues,
20+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const { weaveQueues } = require('.');
2+
const Queue = require('../index');
3+
4+
describe('Weave two queues using weaveQueues()', () => {
5+
it('Should weave be a function', () => {
6+
expect(typeof weaveQueues).toEqual('function');
7+
});
8+
9+
it('Should weave 2 queues', () => {
10+
const q1 = new Queue();
11+
const q2 = new Queue();
12+
13+
q1.add('Hello');
14+
q2.add(1);
15+
q1.add('World');
16+
q2.add(2);
17+
q2.add(3);
18+
19+
const q3 = weaveQueues(q1, q2);
20+
21+
expect(q3.remove()).toEqual('Hello');
22+
expect(q3.remove()).toEqual(1);
23+
expect(q3.remove()).toEqual('World');
24+
expect(q3.remove()).toEqual(2);
25+
expect(q3.remove()).toEqual(3);
26+
});
27+
});

0 commit comments

Comments
 (0)
Please sign in to comment.