MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / MyQueue

Class MyQueue

stacks/queue-via-stacks.js:1–37  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class MyQueue {
2 constructor() {
3 this.stackNewest = new Stack();
4 this.stackOldest = new Stack();
5 }
6
7 size() {
8 return this.stackNewest.size() + this.stackOldest.size();
9 }
10
11 push(x) {
12 /* Push into stackNewest; wich always has the newes elements on top */
13 this.stackNewest.push(x);
14 }
15
16 /* muve elements from stackNewest into stackOldest. This is usually done so that
17 we can do operations on stackOldest. */
18 #shiftStacks() {
19 if (this.stackOldest.isEmpty()) {
20 while (!this.stackNewest.isEmpty()) {
21 this.stackOldest.push(this.stackNewest.pop());
22 }
23 }
24 }
25
26 pop() {
27 this.#shiftStacks(); // Ensure stackOldest has the current elements
28 return this.stackOldest.pop();
29 }
30 peek() {
31 this.#shiftStacks(); // Ensure stackOldest has the current elements
32 return this.stackOldest.peek();
33 }
34 empty() {
35 return this.stackNewest.size() + this.stackOldest.size() === 0;
36 }
37}
38
39class Stack {
40 constructor() {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected