How to implement stack in TypeScript

1 Answer

0 votes
class Stack {
    private items:number[];
 
    constructor() {
        this.items = [];
    }
     
    add(element: number) : number {
        return this.items.push(element);
    }
     
    size() {
        return this.items.length;
    }
     
    pop() {
        if (this.items.length > 0) {
            return this.items.pop();
        } else return -1
    }
     
    peek() {
        return this.items[this.items.length - 1];
    }
 
    isEmpty() {
        return this.items.length == 0;
    }
      
    print() {
        let s:string = ""
        for (let i = 0; i < this.items.length; i++) {
            s += this.items[i] + ", ";
        }
        console.log(s);
    }
 
    delete() {
        this.items = [];
    }
}
 
let stack = new Stack();
 
stack.add(3);
stack.add(0);
stack.add(7);
stack.add(2);
stack.add(9);
stack.add(5);
 
stack.print();
 
stack.pop();
stack.print();
 
console.log(stack.peek());
 
console.log("size: " + stack.size());
 
console.log(stack.isEmpty());
 
stack.pop();
stack.print();
 
stack.delete();
stack.print();
 
 
 
 
/*
run:
 
"3, 0, 7, 2, 9, 5, " 
"3, 0, 7, 2, 9, " 
9 
"size: 5" 
false 
"3, 0, 7, 2, " 
"" 
 
*/

 



answered Jan 28, 2022 by avibootz
edited Jan 28, 2022 by avibootz
...