Problem overview
A stack is a pile where you only touch the top. The last value you put in is the first one you take out, which is called LIFO (last in, first out), like a pile of plates. This lesson builds a class MyStack that holds whole numbers in a private array field named #data, with four operations:
push(value)puts a value on top and returns nothing.pop()removes the top value and returns it.peek()returns the top value and leaves it on the stack.size()returns how many values the stack holds.
The lesson's tests never call pop or peek on an empty stack, and the stack must keep working after it becomes empty. The driver pushes 10, 20 and 30, then peeks, pops and pushes again. It prints:
Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1
After the three pushes the top is 30 and the size is 3. The first pop returns 30. The next two return 20 and then 10, which is the reverse of the order they went in. The stack is then empty, and after pushing 7 the top is 7.
Approach: the end of an array is the top
A JavaScript array already behaves like a stack at its end. Adding to the end and removing from the end are both cheap, and the value added last is always the last element. So the design is to keep the values in an array and treat its end as the top of the stack.
Putting the top at the front would work but would be a worse choice: inserting or removing at index 0 means shifting every other element. Using the end avoids that.
The array lives in a private field. Code outside the class can use only the four methods, so nobody can reorder the values or reach into the middle of the stack. That is the point of building a stack as its own class instead of passing a bare array around.
Step by step
- Declare the class
MyStack. The driver'snew MyStack()builds an object from it. - Declare the private field
#dataand start it as an empty array. The initial value is written right in the field declaration, so every new stack starts empty and has its own array. - Write
push. It takesvalueand calls the array's ownpushonthis.#data. Methods in a class have nofunctionkeyword. - Write
pop. It returns what the array'spopremoves from its end. That one call both removes the last item and hands it back. - Write
peek. It returns the last item by index:this.#data.length - 1. With three values the last index is 2. Reading by index removes nothing. - Write
size. It returns the array'slength, since there is one array item per value.
The solution in JavaScript
class MyStack {
#data = [];
push(value) {
this.#data.push(value);
}
pop() {
return this.#data.pop();
}
peek() {
return this.#data[this.#data.length - 1];
}
size() {
return this.#data.length;
}
}
let s = new MyStack();
s.push(10);
s.push(20);
s.push(30);
console.log("Top: " + s.peek());
console.log("Size: " + s.size());
console.log("Pop: " + s.pop());
console.log("Size: " + s.size());
console.log("Pop: " + s.pop());
console.log("Pop: " + s.pop());
console.log("Empty size: " + s.size());
s.push(7);
console.log("Top: " + s.peek());
console.log("Size: " + s.size());
A few JavaScript details are worth a closer look:
- Two different
pushmethods.MyStack.pushis yours. Inside it,this.#data.push(value)calls the array's built-in method. They don't clash, because they belong to different objects. - Private fields.
#datais visible only inside the class body. Outside,s.datais just an unrelated property that readsundefined, and writings.#datais a syntax error. - A field initialiser runs for each object.
#data = [];creates a new array every timenew MyStack()runs. Two stacks never share their values: pushing onto one leaves the other's size unchanged. sizeis a method. Call it ass.size(). Writings.sizegives the function itself, not a number.- Indexing past the ends gives
undefined. Reading an array at an index that doesn't exist doesn't throw, and a negative index like-1is not "the last item" either:arr[-1]isundefined. That is whypeekcomputeslength - 1.
Complexity
Time: O(1) per operation in the usual case. Each method touches only the end of the array or reads its length. An occasional push may need the engine to grow the array's storage, but that cost averages out over many pushes.
Space: O(n) for n values, the array that holds them. The methods add only a constant amount on top.
Edge cases and common mistakes
- Using
shiftorunshift. They work on the front of the array and shift every other element. The values would then come out in the wrong order unless every method used the same end. - Making
peekremove the value.peekmust leave the size unchanged. Callingpopinside it would shrink the stack. - Forgetting
returninpop. The value would still be removed, but the caller would getundefinedand the driver would printPop: undefined. - Empty stack. The tests never do this, but in this implementation
pop()andpeek()on an empty stack both returnundefinedwithout throwing, andsize()returns 0. - Reusing a stack after it empties. Nothing special is needed: after the last pop the array is empty, and pushing 7 works as on a new stack.
- Dropping the
#. A plain fielddatawould let outside code change the stack in ways its methods don't allow.
Testing
- A new stack:
size()returns 0. - Push 1, then push 2:
peek()returns 2 twice in a row, andsize()stays 2. - Push 10, 20, 30 and pop once: the result is 30 and the size is 2.
- Push 5 on one stack while another is empty: the first has size 1 and the second still has size 0.
