Implement a basic data structure like a Queue or Stack.

Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer

Stack (LIFO - Last-In, First-Out):

Uses an array's push and pop methods.

class Stack {
  constructor() {
    this.items = [];
  }
  
  push(element) { this.items.push(element); }
  pop() { return this.items.pop(); }
  peek() { return this.items[this.items.length - 1]; }
  isEmpty() { return this.items.length === 0; }
  size() { return this.items.length; }
}

Queue (FIFO - First-In, First-Out):

Uses an array's push and shift methods. Note: shift() can be inefficient for large arrays.

class Queue {
  constructor() {
    this.items = [];
  }
  
  enqueue(element) { this.items.push(element); }
  dequeue() { return this.items.shift(); }
  front() { return this.items[0]; }
  isEmpty() { return this.items.length === 0; }
  size() { return this.items.length; }
}