| 1 | class 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 | |
| 39 | class Stack { |
| 40 | constructor() { |
nothing calls this directly
no outgoing calls
no test coverage detected