Write a Generic Stack Class

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write a class Stack<T>: push(item) adds an item to the top, pop() removes and returns the top item, peek() returns it without removing it, and size is how many items it holds. pop and peek return undefined when the stack is empty. Type it so a Stack<number> only takes numbers, and pop and peek return T | undefined, so callers must handle the empty case.

Your code must pass

  • Pops items last in, first out
  • peek shows the top item without removing it
  • Returns undefined when empty
  • Has no type errors
  • pop and peek return T or undefined
  • Rejects pushing the wrong type