An admin changes the address on a shipment form, then realises it's wrong and presses Ctrl+Z. How does the app know what the form held before the change? From a snapshot taken before it.
The Memento pattern keeps a snapshot of an object's state before the object changes, so that state can be brought back later. It's the base of every undo and redo button. Picture taking apart a bicycle brake. Before you start, you take a photo of it. If the reassembly goes wrong, the photo shows how to put it back. You don't scribble on the photo, you keep it in an album, and when your phone runs out of space, the oldest photo is the one deleted.
The problem: a form with no way back
The shipment draft form holds the recipient, the service, the weight and the address. The admin changes the service to express, then the city to Bath, then realises both were wrong. If the old state wasn't kept anywhere, there's nothing to bring back.
In the Command lesson, each action kept how to cancel itself. For a form with many fields, that means writing an inverse for every field. Memento takes a simpler route: before every change, keep the whole draft.
Three roles: originator, memento, caretaker
// Originator: the form that makes and restores snapshots
const form = {
draft: {
recipient: "Mrs. Sari",
service: "regular",
kg: 2,
address: { street: "5 Jasmine Street", city: "Bristol" },
},
save() {
return structuredClone(this.draft) // memento: a full copy, address copied too
},
restore(memento) {
this.draft = structuredClone(memento)
},
}
// Caretaker: keeps the snapshots, never changes what is inside
const MAX_HISTORY = 5
const history = { undo: [], redo: [] }
function edit(field, change) {
history.undo.push(form.save()) // save BEFORE the change
if (history.undo.length > MAX_HISTORY) history.undo.shift() // drop the oldest
history.redo.length = 0 // a new edit cancels redo
change(form.draft)
}
function undo() {
if (history.undo.length === 0) return false
history.redo.push(form.save())
form.restore(history.undo.pop())
return true
}
function redo() {
if (history.redo.length === 0) return false
history.undo.push(form.save())
form.restore(history.redo.pop())
return true
}
function summary(d) {
return d.service + ", " + d.kg + " kg, " + d.address.city
}
- The Originator is the object whose state is kept:
form. Only it knows how to make a snapshot (save) and restore one (restore). - The Memento is the snapshot itself: the object
save()returns. Nobody may change it once it's made. - The Caretaker keeps the history:
history, with two stacks. It stores and hands back mementos, but never reads or changes what's inside them. structuredClone(x)is a built-in function (modern browsers and Node 17 and up) that makes a full copy, including objects inside the object, likeaddress.editkeeps the snapshot before the draft changes. That's what undo brings back later.history.redo.length = 0empties the redo stack on every new edit. The reason is in the next section.
Undo and redo, step by step
edit("service", (d) => { d.service = "express" })
edit("city", (d) => { d.address.city = "Bath" })
undo()
undo()
redo()
edit("weight", (d) => { d.kg += 1 })
console.log(redo()) // false
| step | the draft after it | in the undo stack | in the redo stack |
|---|---|---|---|
| start | regular, 2 kg, Bristol | 0 | 0 |
edit("service", ...) |
express, 2 kg, Bristol | 1 | 0 |
edit("city", ...) |
express, 2 kg, Bath | 2 | 0 |
undo() |
express, 2 kg, Bristol | 1 | 1 |
undo() |
regular, 2 kg, Bristol | 0 | 2 |
redo() |
express, 2 kg, Bristol | 1 | 1 |
edit("weight", ...) |
express, 3 kg, Bristol | 2 | 0 |
redo() |
false, the draft doesn't change |
2 | 0 |
Undo puts the current draft on the redo stack, then restores the top snapshot from the undo stack. Redo does the opposite. When a new edit comes after an undo (edit("weight")), the redo stack is emptied. That edit starts a new branch, so the "express, 2 kg, Bath" snapshot in redo doesn't fit anymore: redoing to it would throw away the weight that was just changed. Undo in text editors and design apps behaves the same way.
A shallow copy: a snapshot that changes too
Now save() is written with spread:
save() {
return { ...this.draft } // a shallow copy
},
restore(memento) {
this.draft = { ...memento }
},
Take a guess first. The shipment draft has address: { street: "5 Jasmine Street", city: "Bristol" }, and its snapshot is made with { ...this.draft }. The admin changes the city to Bath (d.address.city = "Bath"), then presses undo. Which city shows?
Run edit("city", ...) then undo(), and the city stays Bath. { ...draft } only copies the top fields. service and kg hold a string and a number, so their values are copied. But address holds an object, and only its reference is copied: the snapshot and the draft hold the same address object. d.address.city = "Bath" changes that object, and the snapshot changes with it. Every snapshot made with spread uses the same address, so no number of undos brings Bristol back.
Three ways to fix it:
structuredClone: a full copy, includingDate,MapandSet. Functions can't be copied (it throwsDataCloneError), but a form draft is only data anyway.JSON.parse(JSON.stringify(draft)): also a full copy, but JSON has noDatetype. Dates become text, so after a restore,draft.shipDate.getDate()throws aTypeError.- Don't change the inner objects: make new ones,
form.draft = { ...d, address: { ...d.address, city: "Bath" } }. A shallow snapshot is then safe, and the parts that didn't change are shared without being copied. That's how Redux and Immer work.
Memory: every snapshot has a cost
One snapshot of the draft above is only about 100 bytes, so 5 snapshots go unnoticed. It's a different story when the draft carries a parcel photo as a data URL of about 300 KB. structuredClone copies the photo too, in every snapshot: 5 snapshots come to about 1,500 KB, and an uncapped history with 200 edits to about 60 MB.
- Cap the history.
MAX_HISTORYwithshift()drops the oldest snapshot when the stack is full. - Keep only what undo needs. A photo the form doesn't edit doesn't have to be in the snapshot.
- Store the change, not the whole state. For a big state with small changes, keep
{ field: "city", old: "Bristol", new: "Bath" }, and undo writes the old value back. This is called an incremental memento, and it has the same shape as the Command from the previous lesson. - Don't snapshot every keystroke. Keep one per meaningful action, say when a field is done changing.
Exercise: an editor with undo and redo
The exercise uses the same pattern for text. createEditor(maxHistory) returns an object with five methods. Its state is a single string, text, and a JavaScript string can't be changed in place, so the string itself is already a safe snapshot. Nothing needs copying.
type(str): pushtextonto the undo stack before addingstr. If the undo stack holds more thanmaxHistory, drop the oldest withshift(). Empty the redo stack. Thentext += str.getText(): returntext.undo(): if the undo stack is empty,return false. Otherwise pushtextonto the redo stack, take the top snapshot withpop(), thenreturn true.redo(): the opposite: pushtextonto the undo stack, take from the redo stack,return true, orfalsewhen empty.historySize(): return{ undo: ..., redo: ... }, the length of both stacks.
With createEditor(3), the starter prints 10 lines: an empty string, Hello, World, 3, true, Hello, (with a space at the end), 1, true, Hello, World, then after an undo and type('!!'): Hello, !! and 0. Also graded: createEditor(2) typed a, b, c keeps only 2 snapshots.
⚠️ Why does undo or redo miss?
- A shallow copy for nested objects.
{ ...draft }sharesaddresswith the draft, so undo doesn't bring Bristol back. UsestructuredClone, or don't change the inner objects. - Taking the snapshot after the change. The first undo then restores the same state as now, and nothing seems to happen.
- Forgetting to empty redo. A redo after a new edit jumps to the old branch and throws the new edit away.
- An uncapped history, or a snapshot per keystroke. With a 300 KB photo, 200 snapshots are about 60 MB.
- In the exercise: an undo that doesn't put
texton the redo stack.redo()then returnsfalse, andhistorySize().redostays0.
TL;DR: Memento keeps a snapshot of the state before each change so it can be brought back. Its three roles: the originator (form, with save and restore), the memento (the snapshot, changed by nobody), and the caretaker (history, which keeps the undo and redo stacks without reading inside them). Undo moves the current state to redo and restores the top snapshot; a new edit empties redo. { ...draft } only copies the top fields, so address is shared and undoing the city keeps Bath; structuredClone copies everything, JSON breaks Date. Every snapshot costs memory: cap it with MAX_HISTORY, drop the old with shift(), and for a big state keep only the change (Command). In the exercise: snapshot text before type, undo and redo return true or false, and historySize() returns { undo, redo }.
⚡ A snapshot before the change
Write:
function edit(field, change) {
history.undo.push(form.save()) // save BEFORE the change
if (history.undo.length > MAX_HISTORY) history.undo.shift() // drop the oldest
history.redo.length = 0 // a new edit cancels redo
change(form.draft)
}
Meaning: Memento keeps a snapshot of an object's state before it changes, so it can be brought back. Its three roles: the originator (form, which makes and restores snapshots), the memento (the snapshot), and the caretaker (history, which keeps the history without changing what's inside).
⚡ A new edit empties redo
Meaning: Undo moves the current draft onto the redo stack, then restores the top snapshot from the undo stack. A new edit after an undo starts a new branch, so the redo stack is emptied.
⚡ A shallow copy changes too
Guess first: snapshots are made with { ...this.draft }. The admin changes d.address.city to Bath, then presses undo. Which city shows?
Still Bath. { ...draft } only copies the top fields, so the snapshot and the draft hold the same address object.
Meaning: Use structuredClone for a full copy. Every snapshot costs memory, so cap the history with MAX_HISTORY.