Skip to content

Commit 4a1599b

Browse files
committed
--update: immitate Queue using 2 stacks
1 parent 6b4d8e8 commit 4a1599b

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
const Queue = require('.');
2+
3+
describe('Immitated Queue using 2 Stacks', () => {
4+
it('Should be class', () => {
5+
expect(typeof Queue.prototype.constructor).toEqual('function');
6+
});
7+
8+
describe('Queue API', () => {
9+
let queue = null;
10+
11+
beforeEach(() => {
12+
queue = new Queue();
13+
});
14+
15+
it('Should add() element to a queue', () => {
16+
queue.add(5);
17+
expect(queue.data).toEqual([5]);
18+
});
19+
20+
it('Should remove() an element from the queue', () => {
21+
queue.add(2);
22+
queue.add(3);
23+
24+
expect(queue.remove()).toEqual(2);
25+
expect(queue.data).toEqual([3]);
26+
});
27+
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+
44+
it('Should maintain the order of elements', () => {
45+
// first in first out
46+
queue.add(2);
47+
queue.add(1);
48+
queue.add(4);
49+
queue.add(3);
50+
51+
expect(queue.remove()).toEqual(2);
52+
expect(queue.remove()).toEqual(1);
53+
expect(queue.remove()).toEqual(4);
54+
expect(queue.remove()).toEqual(3);
55+
});
56+
});
57+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
const Stack = require('../index');
2+
3+
class ImmitateQueue {
4+
constructor() {
5+
this.stackA = new Stack();
6+
this.stackB = new Stack();
7+
this.data = this.stackA.data;
8+
}
9+
10+
add(element) {
11+
this.stackA.push(element);
12+
this.data = this.stackA.data;
13+
}
14+
15+
peek() {
16+
while (this.stackA.peek()) {
17+
this.stackB.push(this.stackA.pop());
18+
}
19+
20+
const element = this.stackB.peek();
21+
22+
while (this.stackB.peek()) {
23+
this.stackA.push(this.stackB.pop());
24+
}
25+
this.data = this.stackA.data;
26+
return element;
27+
}
28+
29+
remove() {
30+
while (this.stackA.peek()) {
31+
this.stackB.push(this.stackA.pop());
32+
}
33+
34+
const element = this.stackB.pop();
35+
36+
while (this.stackB.peek()) {
37+
this.stackA.push(this.stackB.pop());
38+
}
39+
40+
this.data = this.stackA.data;
41+
return element;
42+
}
43+
}
44+
45+
module.exports = ImmitateQueue;

0 commit comments

Comments
 (0)