The challenge
Write a class Stack with methods push(item), pop() (removes and returns the top item, or undefined if empty), peek() (returns the top item without removing it), and a getter size. Keep the items in a private field.
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
- Pop returns the last item pushed:
(() => { const s = new Stack(); s.push(1); s.push(2); return [s.pop(), s.size]; })()gives[2, 1] - Peek doesn’t remove:
(() => { const s = new Stack(); s.push("a"); return [s.peek(), s.size]; })()gives["a", 1] - Popping an empty stack gives undefined:
new Stack().pop()givesundefined - The items are private:
Object.keys(new Stack()).lengthgives0
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
#items = []; declares a private field.
Hint 2
Arrays already have push and pop. peek is this.#items.at(-1).
Hint 3
A getter looks like get size() { return … }.
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
class Stack {
#items = [];
push(item) {
this.#items.push(item);
}
pop() {
return this.#items.pop();
}
peek() {
return this.#items.at(-1);
}
get size() {
return this.#items.length;
}
}
Learn what you need
This exercise uses what Sophomore Year: Classes & Object-Oriented JavaScript teaches. Read those notes first if any of it is new.