Skip to content

Commit 47d7a9c

Browse files
authored
chore(3.4): rewrite to es6 (careercup#65)
1 parent f206946 commit 47d7a9c

File tree

1 file changed

+32
-30
lines changed

1 file changed

+32
-30
lines changed

chapter03/3.4 - Queue via Stacks/queueViaStacks.js

Lines changed: 32 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,49 @@
11
var Stack = require('./../util/Stack');
22

3-
var myQueue = function() {
4-
this.front = new Stack();
5-
this.back = new Stack();
6-
this.backUp = true;
7-
};
3+
class MyQueue {
4+
constructor() {
5+
this.front = new Stack();
6+
this.back = new Stack();
7+
this.backUp = true;
8+
}
89

9-
myQueue.prototype.add = function(value) {
10-
if (!this.backUp) {
11-
while (!this.front.isEmpty()) {
12-
this.back.push(this.front.pop());
10+
add(value) {
11+
if (!this.backUp) {
12+
while (!this.front.isEmpty()) {
13+
this.back.push(this.front.pop());
14+
}
15+
this.backUp = true;
1316
}
14-
this.backUp = true;
17+
this.back.push(value);
1518
}
16-
this.back.push(value);
17-
};
1819

19-
myQueue.prototype.remove = function() {
20-
if (this.backUp) {
21-
while(!this.back.isEmpty()) {
22-
this.front.push(this.back.pop());
20+
remove() {
21+
if (this.backUp) {
22+
while(!this.back.isEmpty()) {
23+
this.front.push(this.back.pop());
24+
}
25+
this.backUp = false;
2326
}
24-
this.backUp = false;
27+
return this.front.pop();
2528
}
26-
return this.front.pop();
27-
};
2829

29-
myQueue.prototype.peek = function() {
30-
if (this.backUp) {
31-
while(!this.back.isEmpty()) {
32-
this.front.push(this.back.pop());
30+
peek() {
31+
if (this.backUp) {
32+
while(!this.back.isEmpty()) {
33+
this.front.push(this.back.pop());
34+
}
35+
this.backUp = false;
3336
}
34-
this.backUp = false;
37+
return this.front.peek();
3538
}
36-
return this.front.peek();
37-
};
3839

39-
myQueue.prototype.isEmpty = function() {
40-
return this.front.isEmpty() && this.back.isEmpty();
41-
};
40+
isEmpty() {
41+
return this.front.isEmpty() && this.back.isEmpty();
42+
}
43+
}
4244

4345
/* TEST */
44-
var m = new myQueue();
46+
var m = new MyQueue();
4547
console.log(m.isEmpty(), true);
4648

4749
m.add('a');

0 commit comments

Comments
 (0)