A stack you can look into without disturbing it
A stack is the first structure most frontend work reaches for: the router history you pop back through, the modal layers you close in reverse order, the parser that matches your JSX tags. It is a list where the only item you can touch is the most recent one.
Implement a Stack class. It is constructed with no arguments and starts empty. push(value) adds a value on top and returns the new size as a number. pop() removes the top value and returns it, or returns undefined when the stack is empty. peek() returns the top value without removing it, or undefined when the stack is empty. size() returns how many values are currently held. isEmpty() returns true when nothing is held and false otherwise.
Examples
const s = new Stack();
s.push("a"); // 1
s.push("b"); // 2
s.peek(); // "b"
s.pop(); // "b"
s.size(); // 1push returns the new size; pop and peek work on the top.
const s = new Stack();
s.pop(); // undefined
s.peek(); // undefined
s.isEmpty(); // trueAn empty stack returns undefined rather than throwing.
What it has to do
pushreturns the size of the stack after the value was added.popreturns values in last-in-first-out order.popandpeekreturnundefinedon an empty stack rather than throwing.peekleaves the stack unchanged.isEmpty()istrueonly whensize()is 0.
Notes
- Every operation is O(1) when the stack is backed by an array that only touches the end.
- Reaching for
.shift()instead of.pop()turns the stack into a queue and makes every operation O(n) — be deliberate about which end you work from.
Stuck? The javascript course covers everything this challenge needs.
- 1.push returns the new size and peek reports the top
- 2.pops in last-in-first-out order
- 3.an empty stack reports undefined instead of throwing
- 4.peek does not remove the value
- 5.isEmpty tracks the stack emptying again
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.