Ad

Let's just hide that the Stack is implemented with an array, so that we're not tempted to use other methods as shift() 😇

Code
Diff
  • class Stack {  // Just to hide the use of array implementation
      constructor() {
        this._items = [];
      }
      push(data) {
        this._items.push(data);
      }
      pop() {
        return this._items.pop();
      }
      length() {
        return this._items.length;
      }
    }
    
    class Queue {
      constructor() {
        this._stack = new Stack();
      }
      enqueue(data) {
        this._stack.push(data);
      }
      dequeue() {
        if (this._stack.length() === 1)
          return this._stack.pop();
        else {
          var tmp = this._stack.pop(), result = this.dequeue();
          this.enqueue(tmp);
          return result;
        }
      }
    }
    • class Stack { // Just to hide the use of array implementation
    • constructor() {
    • this._items = [];
    • }
    • push(data) {
    • this._items.push(data);
    • }
    • pop() {
    • return this._items.pop();
    • }
    • length() {
    • return this._items.length;
    • }
    • }
    • class Queue {
    • constructor() {
    • this._stack = []; // We will be using this array as a stack - only
    • // its push and pop operations will ever be called
    • this._stack = new Stack();
    • }
    • enqueue(data) {
    • this._stack.push(data);
    • }
    • dequeue() {
    • if (this._stack.length === 1)
    • if (this._stack.length() === 1)
    • return this._stack.pop();
    • else {
    • var tmp = this._stack.pop(), result = this.dequeue();
    • this.enqueue(tmp);
    • return result;
    • }
    • }
    • }