Skip to curriculum
Jump to the editor

19.9. A key-value store with undo

Medium
Topics
20–35 min

A settings panel, a spreadsheet or a canvas of shapes keeps its data as keys and values, and the user expects Ctrl+Z to work. Storing a full copy of the data after every change wastes memory when one key out of thousands changed. Instead, each change can remember what it replaced, so undo can put exactly that back.

Write the class UndoableStore in undoable-store.js: a key-value store like a Map, where every set and delete is a step that undo() reverts and redo() applies again. A transaction(fn) makes several changes one step, and undoes them all if fn throws.

Signature

JAVASCRIPT
class UndoableStore {
  get size()             // how many keys the store holds
  get(key)               // the value, or undefined
  has(key)               // true or false
  set(key, value)        // returns the store
  delete(key)            // true if the key was there, otherwise false
  undo()                 // true if a step was undone, otherwise false
  redo()                 // true if a step was redone, otherwise false
  canUndo()              // true or false
  canRedo()              // true or false
  transaction(fn)        // calls fn(store), returns what fn returns
}

Requirements

  1. get, has, set, delete and size behave like a Map. Keys can be any value: 1 and "1" are different keys, objects and NaN work.
  2. set returns the store; delete returns whether the key was there.
  3. Each set or delete is one step. undo() reverts the latest step, newest first, and returns true; with nothing to undo it returns false and changes nothing.
  4. Undo restores the exact earlier state: a key that was absent is removed again, and a key that held undefined holds undefined again (it is not removed).
  5. redo() applies the latest undone step again and returns true, or returns false when there is nothing to redo. canUndo() and canRedo() say whether each would do something.
  6. A new step clears everything there was to redo.
  7. A set of the value a present key already holds (compared with Object.is) and a delete of a missing key change nothing: they record no step and keep redo.
  8. transaction(fn) calls fn with the store and returns its result. Every change made inside is one step: one undo() reverts all of them, one redo() applies all of them, in the right order. A transaction with no change records nothing.
  9. A transaction inside a transaction adds to the outermost one; only the outermost records a step.
  10. If fn throws, every change it made is rolled back, no step is recorded, and the same error is thrown again. When an inner transaction fails and the outer one catches the error, only the inner changes are rolled back.
  11. undo() or redo() inside a transaction throws an Error.
  12. Each store has its own data and steps.

Examples

JAVASCRIPT
const store = new UndoableStore();
store.set("theme", "dark");
store.set("theme", "light");
store.undo();            // true
store.get("theme");      // "dark"
store.undo();            // true
store.has("theme");      // false: it was absent before the first set
store.undo();            // false
store.redo();            // true
store.get("theme");      // "dark"
JAVASCRIPT
const store = new UndoableStore();
store.set("x", 0);
store.transaction((s) => {
  s.set("x", 10);
  s.set("y", 20);
});
store.undo();            // one step: x is 0 again and y is gone
JAVASCRIPT
const store = new UndoableStore();
store.set("count", 1);
try {
  store.transaction((s) => {
    s.set("count", 2);
    throw new Error("validation failed");
  });
} catch (error) {
  // error.message === "validation failed"
}
store.get("count");      // 1: rolled back

Environment

  • Plain JavaScript in a browser page; the tests create instances of the global class UndoableStore from undoable-store.js.
  • fn is synchronous; async transactions are not part of this problem.
  • Store each change with what it replaced, not a full copy of the store per step.
  • A limit on the number of steps is not part of this problem.

Hints

  1. Before a key changes, what two facts about it do you need to be able to put it back?
  2. When undo puts old values back, what does redo need, and when can you capture it?
  3. For an inner transaction that fails, how do you know which of the collected changes are its own?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…