Undo and redo

Two stacks: what you can undo and what you can redo. Any new change clears the redo stack.

JavaScript · Undo and redoAdvanced
class History {
  #past = [];
  #future = [];
  constructor(initial) { this.state = initial; }

  push(next) {
    this.#past.push(this.state);
    this.state = next;
    this.#future = [];
  }
  undo() {
    if (!this.#past.length) return this.state;
    this.#future.push(this.state);
    return (this.state = this.#past.pop());
  }
  redo() {
    if (!this.#future.length) return this.state;
    this.#past.push(this.state);
    return (this.state = this.#future.pop());
  }
  get canUndo() { return this.#past.length > 0; }
  get canRedo() { return this.#future.length > 0; }
}

const h = new History('a');
h.push('b'); h.push('c');
undoredohistorystack