Přejít k hlavnímu obsahu
← ⚡ JavaScript & the browser·Modul C9 · Lekce 10
ÚkolBuild 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
Teorie

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 se a začni programovat

Teorie je otevřená pro každého. Editor, živý náhled a check se odemknou s 7denní zkušební verzí zdarma — karta vyžadována, zrušíš kdykoli.

Registrace — zkušební verze zdarma →

Prvních 10 lekcí v každé trase je zdarma. Karta není potřeba.

← PředchozíDalší lekce →

Jeden tip k Pythonu nebo webu denně — e-mailem

Krátké, ručně psané, žádný spam. Odhlásit jedním klikem.