Naar hoofdinhoud
← ⚑ JavaScript & the browserΒ·Module C9 Β· Les 10
OpdrachtBuild 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
Theorie

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

πŸ”’

Registreer om te beginnen met coderen

Theorie is voor iedereen. De editor, live preview en check ontgrendelen met een 7-daagse gratis proefperiode β€” kaart vereist, opzegbaar.

Registreren β€” gratis proef β†’

De eerste 10 lessen in elke track zijn gratis. Geen kaart nodig.

← VorigeVolgende les β†’

EΓ©n Python- of web-tip per dag β€” per e-mail

Kort, met de hand geschreven, geen spam. Met één klik afmelden.