Prejsť na hlavný obsah
← ⚡ JavaScript & the browser·Modul C9 · Lekcia 10
ÚlohaBuild createUndoStack(key, initial) with .current() / .push(state) / .undo() / .size() per the theory. Use storage key 'doc'. Start with {text:'a'}. push({text:'ab'}). push({text:'abc'}). Log size (3), current().text ('abc'). undo() and log .text ('ab'). undo() and log .text ('a'). undo() once more — should stop, log .text ('a') again.

Capstone: undo stack with structuredClone + localStorage

275 XP15 min
Teória

Persistent undo with native primitives

A real-world feature that ties C9 ideas together:

  • structuredClone — snapshot state into the stack.
  • localStorage + JSON — persist the stack across reloads.
  • No library.
function createUndoStack(key, initial) {
  const stack = JSON.parse(localStorage.getItem(key) || "null") || [initial];
  function save() { localStorage.setItem(key, JSON.stringify(stack)); }

  return {
    current() { return stack[stack.length - 1]; },
    push(state) { stack.push(structuredClone(state)); save(); },
    undo() {
      if (stack.length > 1) stack.pop();
      save();
      return stack[stack.length - 1];
    },
    size() { return stack.length; },
  };
}

What you get

  • push(state) saves a snapshot. structuredClone means later mutations don't corrupt history.
  • undo() pops the last snapshot and returns the previous one. Stops at the initial state.
  • Reload the page and the stack is still there.

The capstone

Build that exact shape and walk through a small editing flow: start, push two states, undo once, undo once more, undo a third time (should stop at initial).

🔒

Zaregistruj sa a začni programovať

Teória je otvorená pre každého. Editor, živý náhľad a kontrola sa odomknú so 7-dňovou bezplatnou skúškou — karta potrebná, zruš kedykoľvek.

Registrácia — bezplatná skúška →

Prvých 10 lekcií v každej trase je zdarma. Karta nie je potrebná.

← PredchádzajúcaĎalšia lekcia →

Jeden tip k Pythonu alebo webu denne — e-mailom

Krátke, ručne písané, žiadny spam. Odhlásiť jedným klikom.