A stack is LIFO (Last In First Out) list. When you remove elements from the list, the most recently added item is removed first. In this lesson we'll cover how to implement a stack using TypeScript. Stack based questions are common in technical interviews, so it useful to be familiar with how they work.
[00:00] Let's begin by creating a new class named Stack. This Stack is going to hold a collection of data. Traditionally, in a Stack, each piece of that data is called a frame. Let's create that variable. [00:20] For now, I will just initialize it to an empty array. The first method we're going to define is push. Push takes one argument item of type 'any' and it places it on the top of the stack. Here we're using the push [00:40] method built into our array to add our new item to the top of the Stack. I've already written some tests for this, let's go check them out. This test creates a new Stack and it pushes 2 elements to it. Our assertion here checks that the internal state of the stack is what we expect it to be. The tests are running on watch mode, and as you can see, the [01:00] test is passing. The next method we're going to define is 'pop'. The stack is a last in, first out list. Pop removes the last element from that list and returns it to us. [01:20] Let's take a look at the tests. Here, we create a new stack, we push 2 elements to it, and then we call pop. What this should do is return the last element that we've added, in this case 2. As you can see, that test now passes. Let's define the peak method. [01:48] PEAK is similar to POP. It takes the last element in our collection and returns it. The difference, however, is that it doesn't remove it from the list. Let's go check the tests. This test is almost identical to the one for POP. We create a new stack, we push 2 elements to it, then we call stack. Peep. And what we're hoping to see is the last element we push to the stack [02:07] too. If we check the tests, we can see that it's passing. We'll create the size method next. This one's pretty straightforward. We basically just return the length of the array. Again, we'll hop over to the tests. [02:29] Here, we create a new stack, we push 2 elements to it, and then we're checking that the size is what we expect it to be. And as you can see, that test is passing. The final method we'll create is 'isEmpty'. [02:49] This one's pretty straightforward too. We're checking that the length of the array is 0. And if we hop over to the tests, Here we create a new stack and we check that it's empty. Then we push an element to it and we check that it's no longer empty. Let's see how we've done. And our test is passing.