Stack in Typescript

by Preetha Srinivasan

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css">
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>

TypeScript

class Stack {

  data: any[];
  count: number = 0;
  size: number = 10;

  constructor(){
   this.data = new Array(this.size);
  }
  
  constructor(size: number) {
    this.size = size;
    this.data = new Array(size);
  }

  push(item: any) {
    if (this.count < this.size) {
      this.data[this.count] = item;
      this.count++;
    } else {
      console.log("The stack is full");
    }
  }

  pop() {
    if (!this.isEmpty()) {
      const index = this.count - 1;
      const value = this.data[index];
      this.count--;
      return value;
    }
  }

  sizeOfStack() {
    return this.count;
  }

  isEmpty() {
    return this.count == 0;
  }

  print() {
    this.data.map(item => {
      console.log(item);
    })
  }

}

describe("Stack tests", function() {
    
  it("Should push an element into the stack", function() {
    var stack = new Stack();
      [1, 2, "test", {
       x: 1,
       y: 2
       }, 5].map(item => {
         stack.push(item);
         });
         expect(stack.sizeOfStack()).toEqual(5);
     });
   
   
   it("Should pop an element from the stack", function() {
    var stack = new Stack();
      [1, 2, 5].map(item => {
         stack.push(item);
         });
         expect(stack.sizeOfStack()).toEqual(3);
         var value = stack.pop();
         expect(value,5);
         expect(stack.sizeOfStack()).toEqual(2);
     });
   
   
   it("Should check if the stack is empty", function() {
    var stack = new Stack();
    expect(stack.isEmpty()).toEqual(true);
    stack.push(1);
    expect(stack.isEmpty()).toEqual(false);
   });
   
   it("Should calculate the size of the stack", function() {
    var stack = new Stack();
    expect(stack.sizeOfStack()).toEqual(0);
    stack.push(1);
    expect(stack.sizeOfStack()).toEqual(1);
   });
   
 });

// load jasmine htmlReporter
(function() {
  var env = jasmine.getEnv();
  env.addReporter(new jasmine.HtmlReporter());
  env.execute();
}());