Generic Stack Implementation in TypeScript
This challenge asks you to implement a generic Stack data structure in TypeScript. Stacks are fundamental data structures that follow the Last-In, First-Out (LIFO) principle, making them useful for tasks like expression evaluation, function call management, and undo/redo functionality. Successfully completing this challenge demonstrates your understanding of generics, classes, and basic data structure principles in TypeScript.
Problem Description
You are required to create a Stack class in TypeScript that can hold elements of any type, specified using generics. The Stack class must implement the following methods:
push(item: T): Adds an item to the top of the stack.pop(): Removes and returns the item at the top of the stack. Should returnundefinedif the stack is empty.peek(): Returns the item at the top of the stack without removing it. Should returnundefinedif the stack is empty.isEmpty(): Returnstrueif the stack is empty,falseotherwise.size(): Returns the number of items in the stack.
The stack should be implemented using an array internally. Ensure your implementation handles edge cases gracefully, particularly when attempting to pop or peek from an empty stack.
Examples
Example 1:
Input:
const stack = new Stack<number>();
stack.push(1);
stack.push(2);
stack.push(3);
Output:
3
Explanation: The last element pushed (3) is returned by `peek()`.
Example 2:
Input:
const stack = new Stack<string>();
stack.push("apple");
stack.push("banana");
stack.pop();
Output:
"apple"
Explanation: "banana" is removed and returned by `pop()`.
Example 3: (Edge Case)
Input:
const stack = new Stack<boolean>();
stack.pop();
stack.peek();
Output:
undefined
undefined
Explanation: Attempting to `pop` or `peek` from an empty stack returns `undefined`.
Constraints
- The stack should be implemented using an array internally.
- The
pushoperation should have a time complexity of O(1). - The
pop,peek,isEmpty, andsizeoperations should have a time complexity of O(1). - The stack should be able to hold any type of data specified by the generic type parameter
T. - The stack should not have a fixed size limit.
Notes
- Consider using a private array to store the stack elements.
- A top pointer (index) can be helpful to track the top of the stack.
- Remember to handle the edge case of an empty stack when implementing
popandpeek. - Focus on code clarity and readability. Use meaningful variable names and comments where necessary.
- Thoroughly test your implementation with various inputs, including edge cases, to ensure its correctness.