StackLoading saved progress…

Stack

Implement a stack — a small data structure that stores items in last-in, first-out (LIFO) order. Think of a stack of plates: you can only add a plate to the top, and you can only take the top plate off. Your stack() factory returns an object with four methods: push, pop, peek, and size.

Signature

function stack(): {
  push(value: unknown): void;   // add value to the top
  pop(): unknown | undefined;   // remove and return the top, or undefined if empty
  peek(): unknown | undefined;  // return the top without removing, or undefined if empty
  size(): number;               // how many items are in the stack
};

Examples

const s = stack();
s.push(1);
s.push(2);
s.push(3);
s.size(); // 3
s.peek(); // 3 — top is the most recently pushed
s.pop();  // 3 — now removed
s.peek(); // 2
s.size(); // 2
const s = stack();
s.pop();   // undefined — empty stack, no error thrown
s.peek();  // undefined — same
s.size();  // 0
s.push('a');
s.pop();   // 'a'
s.pop();   // undefined again — back to empty

Notes

  • LIFO — the most recently pushed value is the next one out. This is the opposite of a queue, which is first-in, first-out.
  • Empty reads return undefinedpop() and peek() on an empty stack must not throw. Returning undefined is the spec.
  • No fixed capacity — push as many items as the caller wants. Don't enforce a max size.
  • Any value is valid — including undefined, null, 0, and false. Don't filter or coerce; the caller decides.
  • Each instance is independent — calling stack() twice gives you two separate stacks; one's pushes don't appear in the other.
  • O(1) push and pop — both operations should run in constant time. A for loop over every item to find the top is wrong.
Loading editor…