Learn Data Structure using TypeScript: 1#Stack

Learn Data Structure using TypeScript: 1#Stack

What is a stack?

Imagine a box full of folded clothes. What does it show? If you put a bunch of folded clothes in a box, you can see a pile of folded clothes on one and another. So if you have to take out the last clothe which is at the bottom of the box. You need to take the rest of the pile of folded clothes.

shirt-clothes_74190-5087.jpg

Similarly, a stack is an Abstract Data Type (ADT), commonly used in most programming languages. This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed last, is read or accessed at first. The operations that is used to insert element in the stack is push and the operation that is used to take out or empty the stack is pop.

Stack.png We can use an Array as an example of a Stack but here we are going to build a separate stack. Let's move on to the implementation part.

Basic Operations We are going to implement following operations as methods. Stack is used for the following two primary operations −

  • push() − Pushing (storing) an element on the stack.
  • pop() − Removing (accessing) an element from the stack.
  • peek() − get the top data element of the stack, without removing it.

There are other operations such as isFull() or isEmpty to determine whether the stack has reached it's size limit or is completely empty respectively.

// Creating a class called Stack
class Stack {
    private count:number;
    private item: Object;

    /**
     * @description: Initializing count and item properties.
     * count is the size of the Stack
     * item is the storage where data will be stored by called the Stack Class's method "push"
     */
    constructor(){
        this.count = 0;
        this.item = {}
    }

    /**
     * @description 
     * @param value: item to be pushed in the stack
     */
    push = (value: number) => {
        this.item[this.count] = value;
        this.count ++;
    }

    /**
     * 
     * @returns last item after taking out the last item on the stack
     */
    pop = () : number | undefined => {
        if(this.count !== 0){
            this.count --;
            const result = this.item[this.count]
            delete this.item[this.count];
            return result;
        }
        return undefined;
    }

    /**
     * 
     * @returns size of the stack
     */
    sizeOf = (): number => this.count;

    /**
     * 
     * @returns last element of the stack
     */
    peek = () : number => this.item[this.count - 1]

}

const myStack = new Stack();
myStack.push(1);
myStack.push(2);
console.log(myStack.sizeOf());
console.log(myStack.peek());
myStack.pop();
console.log(myStack.peek());
console.log(myStack.peek());

So we have successfully figured out how to implement basic functionalities of how the Stack works in Typescript.

That's it. Hope it was helpful for you guys.