The plate pile
A stack only lets you add or remove at the top — last in, first out (LIFO). Undo history, the browser's back button and the JavaScript call stack all work this way. An array's push and pop make a perfect O(1) stack.
A Stack class and an undo history
class Stack {
#items = [];
push(x) { this.#items.push(x); }
pop() { return this.#items.pop(); }
peek() { return this.#items[this.#items.length - 1]; }
get size() { return this.#items.length; }
isEmpty() { return this.#items.length === 0; }
}
let text = "";
const undo = new Stack();
function type(s) { undo.push(text); text += s; }
function undoLast() { if (!undo.isEmpty()) text = undo.pop(); }
type("Hello");
type(", world");
type("!!!");
undoLast();
console.log(text, "| undo levels:", undo.size);