Ctrl+Z, a job queue that runs tonight, and a log of "who changed what" share one idea: the action is kept first. It isn't done right away and then lost.
The Command pattern wraps one action in an object, called a command. It holds how to run the action (do), how to cancel it (undo), and the data it needs. Since it's an object, the action can be kept in a history (a list of the actions that have run), so it can be undone. It can also be put in a queue (a list of actions waiting for their turn) to run later, or logged and replayed (run again). Picture the order slips at a food stall. The waiter writes the order on a slip instead of shouting it at the kitchen. Slips can be queued and cooked in order, crossed out when a customer cancels, and kept as a record at the end of the day. A shouted order is gone once it is heard. In code, the waiter is the code that receives the admin's click, one order slip is one command, and shouting at the kitchen is changing the data directly. The slips waiting to be cooked are the queue, crossing out a slip is undo, and the kept slips are the log.
The problem: buttons that change data directly
In the first admin panel, each button writes parcel.status = "delivered" right away. If the admin misclicks, the old status is overwritten and isn't kept anywhere, so there's nothing to undo. Running 300 status changes tonight, or recording who changed what, isn't possible either: the action happens at that moment and is gone.
Command: an action as an object
In this version, changeStatus makes a command that changes a status. run runs a command and keeps it in history, and undoLast cancels the last one:
const parcel = { trackingNo: "KCL-0001", status: "transit" }
function changeStatus(parcel, newStatus) {
let oldStatus
return {
status: newStatus,
do() {
oldStatus = parcel.status // remembered when it runs
parcel.status = newStatus
},
undo() {
parcel.status = oldStatus
},
}
}
const history = []
function run(cmd) {
cmd.do()
history.push(cmd)
}
function undoLast() {
const cmd = history.pop()
if (!cmd) return false
cmd.undo()
return true
}
run(changeStatus(parcel, "delivering"))
run(changeStatus(parcel, "delivered"))
console.log(parcel.status) // delivered
undoLast()
console.log(parcel.status) // delivering
undoLast()
console.log(parcel.status) // transit
console.log(undoLast()) // false
| step | history |
parcel.status |
|---|---|---|
| start | empty | transit |
run(changeStatus(parcel, "delivering")) |
delivering | delivering |
run(changeStatus(parcel, "delivered")) |
delivering, delivered | delivered |
undoLast() |
delivering | delivering |
undoLast() |
empty | transit |
undoLast() |
empty, returns false |
transit |
changeStatuschanges nothing when it's called. It returns an object with two methods,doandundo.dois allowed as a method name, even though it is also the keyword for thedo...whileloop.do()keeps the current status inoldStatusbefore overwriting it. Without that,undowouldn't know which status to go back to.status: newStatustravels along as data, so the history can be read and replayed later.historyis an array used as a stack:pushputs a command on top, andpoptakes the top one. So undo cancels the last action first.undoLastreturnsfalsewhen the history is empty, instead of throwing an error.rundoesn't know what's inside the command. Another command, saychangeAddress, only needs adoand anundotoo.
Undo must remember, not guess
An undo that keeps nothing has to guess. Here is one that steps back one place in the status list:
const STATUS = ["picked_up", "transit", "delivering", "delivered"]
undo() {
parcel.status = STATUS[STATUS.indexOf(parcel.status) - 1] // one step back
}
The admin changes KCL-0001 from transit straight to delivered (the courier forgot to scan delivering), then presses undo. Take a guess first: what status does the parcel end up with?
The guessing undo steps back one place from delivered, so it gives delivering: a status this parcel never had. The right undo returns transit, because do() already kept it.
When the old status is kept matters too. Keep it inside do(), not when the command is created. Otherwise, a command created at 9 and run at 12 would remember the status at 9, which may have changed since.
Queues and replay: commands as data
A command can be made now and run later. If queue holds 300 status-change commands, queue.forEach(run) runs them all at night, one at a time. A command written as plain data can be saved as JSON and replayed somewhere else. Here log holds two commands written as data:
const log = [
{ type: "changeStatus", trackingNo: "KCL-0001", status: "delivering" },
{ type: "changeStatus", trackingNo: "KCL-0001", status: "delivered" },
]
// say, data restored from this morning's backup
const restored = { "KCL-0001": { trackingNo: "KCL-0001", status: "transit" } }
for (const c of log) run(changeStatus(restored[c.trackingNo], c.status))
console.log(restored["KCL-0001"].status) // delivered
The for loop makes a command again from each entry in log, then runs it on restored. Replaying the same log on the same starting state gives the same final state. Libraries and frameworks often use this pattern:
- A Redux action
{ type: "status/change", payload: { trackingNo, status } }is a command as data. Redux (a library that keeps an app's state) runs it with a reducer, a function that calculates the new state from the action. - A Laravel Job:
dispatch(new SendSms($parcel))saves the job (a task for later) in a queue, for example in the database or in Redis (a database in memory). Then a worker, a separate program that takes jobs from the queue, runs it. - BullMQ: a queue library for Node.js.
queue.add("sendSms", { trackingNo })saves a task in Redis for a Node worker.
A CSS selector isn't a command: it's a style declaration, not an action that can be run, queued or undone.
Exercise: createCommandStack
In the exercise, you write an undo history that works for any command. The starter (the code already in the editor) has counter, two commands (counter += 5 and counter *= 2, each with its opposite) and three console.log calls. You write createCommandStack(), which returns an object with:
execute(cmd): callcmd.do(), then keepcmdin the history.undo(): if the history is empty,return false. Otherwise take the last command, call itsundo(), thenreturn true.size(): the number of commands in the history.
How it runs: counter starts at 0. 0 + 5 = 5, then 5 × 2 = 10, so the first line printed is 10. Two undos take from the top of the stack: 10 / 2 = 5, then 5 - 5 = 0, so the second line is 0. A third undo on an empty history prints false. Also graded: one +5 command runs twice, then is undone once. The result must be 10|2|true|5: the number after two runs, size(), what undo() returns, and the number after the undo.
When you don't need a command
- The action runs once, with no undo, queue or log.
calculateShipping("express", 2)is just called directly. - Its effect leaves your app. Undo can bring
parcel.statusback, but an SMS saying "parcel out for delivery" that was sent can't be taken back. For that you need a new action, such as a correction SMS.
⚠️ Why does undo cancel the wrong thing?
- An undo that guesses. Stepping back one place in the status list gives
deliveringfor a parcel that was never out for delivery. Keep the old state indo(). - Keeping the old state when the command is created. By the time a queued command finally runs, the state it remembers is out of date.
- Undoing from the bottom of the stack. With
shift()instead ofpop(), the first command is the one cancelled first. In the exercise, that gives (10 - 5) / 2 = 2.5, not 0. - Forgetting
return trueorreturn false. In the exercise,console.log(stack.undo())then printsundefined(stackis the object fromcreateCommandStack()).
TL;DR: The Command pattern wraps one action in an object (a command) with do() to run it and undo() to cancel it. Since it's an object, the action can be kept, queued, undone or replayed. An undo history is a stack: the last one in is the first one out. In the exercise, execute calls cmd.do() then pushes it onto the history, and undo takes the last command with pop, calls cmd.undo(), and returns true, or false when the history is empty. Undo must remember the old state kept in do(), not guess it. A parcel changed straight from transit to delivered, then undone by guessing (one step back in the status list), ends up at delivering, a status it never had. Commands as data ({ type, trackingNo, status }) can be queued and replayed. Libraries and frameworks do this: Redux actions, Laravel Jobs, BullMQ. A one-off action with no undo is just called directly.
⚡ An action as an object
Write:
function changeStatus(parcel, newStatus) {
let oldStatus
return {
status: newStatus,
do() {
oldStatus = parcel.status // remembered when it runs
parcel.status = newStatus
},
undo() {
parcel.status = oldStatus
},
}
}
Meaning: The Command pattern wraps one action in an object (a command) with do() to run it and undo() to cancel it, so the action can be kept, queued or undone. Calling changeStatus doesn't change anything yet. do() makes the change, after keeping the current status in oldStatus for undo().
⚡ The history is a stack
Meaning: The history is an array of the commands that have run, and it's used as a stack: the last one in is the first one out. run(cmd) calls cmd.do(), then puts that command on top of the history with push. undoLast() takes the last command (cmd) with pop, calls cmd.undo(), and returns true, or false when the history is empty.
⚡ Undo must remember, not guess
Guess first: the admin changes KCL-0001 from transit straight to delivered, then presses a guessing undo. This undo keeps no old status, so it steps back one place in the status list (picked_up, transit, delivering, delivered). What status does it end up with?
delivering: a status this parcel never had. The right undo returns transit, because do() already kept it.
Meaning: Keep the old status inside do(), not when the command is created. Otherwise, a command created at 9 and run at 12 would remember the status at 9, which may have changed since.