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.
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
};
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
undefined — pop() and peek() on an empty stack must not throw. Returning undefined is the spec.undefined, null, 0, and false. Don't filter or coerce; the caller decides.stack() twice gives you two separate stacks; one's pushes don't appear in the other.for loop over every item to find the top is wrong.