Preskoči na glavni sadržaj
← ⚡ JavaScript & the browser·Modul C9 · Lekcija 10
ZadatakBuild 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
Teorija

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).

🔒

Registriraj se i počni kodirati

Teorija je otvorena svima. Editor, pregled uživo i provjera otključavaju se s 7-dnevnim besplatnim probnim periodom — potrebna kartica, otkaži kad god.

Registracija — besplatan probni period →

Prvih 10 lekcija u svakom smjeru je besplatno. Bez kartice.

← PrethodnaSljedeća lekcija →

Jedan Python ili web savjet dnevno — emailom

Kratko, ručno pisano, bez spama. Odjavi se jednim klikom.