Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 57 ยท Low-Level Design Projects

Project: Text Editor with Undo and a Chess Engine Core

Build a text editor with undo and redo using Command and Memento, then model a chess core with Strategy for piece movement and Composite for armies.

Two projects finish this chapter, and both are favorites in design interviews because they are small enough to finish and rich enough to show real design thinking. The first is a text editor with undo and redo. It needs a way to turn user actions into objects you can reverse. The second is the core of a chess engine: a board, pieces that move in different ways, and moves that can be taken back.

Both lean on Command. The editor adds Memento for the actions that are hard to reverse. The chess core adds Strategy for movement rules and Composite for counting material. Follow the steps from How to Approach a Low-Level Design Problem: requirements, entities, API, patterns, failure paths and extensions.

What each project teaches

Text editor Every edit is an object that can undo itself.
Memento Snapshots reverse edits that have no easy inverse.
Chess moves One movement strategy per kind of piece.
Composite Pieces and groups answer the same question.
1 / 2

Part 1: a text editor with undo and redo

Requirements

  • The editor holds one document of text.
  • The user can insert text at a position, delete a range, and replace every occurrence of a word.
  • Undo reverses the last action; redo repeats an undone action. Doing a new action after an undo clears what could be redone.
  • Out of scope: cursors and selections, rich formatting, files, and merging many keystrokes into one undo step (a real editor groups typing, as noted in the extensions).

Entities

Document is the receiver: it knows how to insert and delete text and nothing about history. Editor is the invoker: it runs commands and keeps two stacks. Each action is a Command with execute and undo. Splitting the three jobs makes each class easy to test. The Command pattern stores what to do; the editor stores what has been done.

classDiagram
  class Editor {
    +run(command)
    +undo()
    +redo()
  }
  class Command {
    <<interface>>
    +execute(doc)
    +undo(doc)
  }
  class Document {
    +insert(pos, text)
    +delete(pos, length) string
    +snapshot() Snapshot
    +restore(snapshot)
  }
  Editor --> Command
  Editor --> Document
  Command ..> Document
  Command <|.. InsertCommand
  Command <|.. DeleteCommand
  Command <|.. ReplaceAllCommand

The editor runs commands against a document. Each command can reverse itself.

Command and Memento together

Insert and delete have natural inverses. Undoing an insert deletes the same range. Undoing a delete inserts the removed text back, so DeleteCommand must remember what it removed. That memory is a tiny memento.

"Replace all" is different. You cannot reverse it by replacing the new word back, because the new word might have existed before (replacing "cat" with "dog" in "dog cat" cannot be undone by replacing "dog" with "cat"). The reliable approach is to take a snapshot of the document before the command runs and restore it on undo. The snapshot is a Memento: an immutable copy of state that only the document can create and restore. Its owner (the command) never looks inside.

Node.js Text editor with Command and Memento

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check the line after "undo replace all": the text is back to its earlier form, including the word that the replace had changed. A snapshot is the safe tool when no neat inverse exists.

Failure paths and extensions

Out-of-range positions throw a RangeError before any history is recorded, because execute fails before run pushes the command. That matters: a failed command must never end up on the undo stack. Extensions fit easily:

  • Grouping typing: let Editor.run ask the previous command whether it can mergeWith the new one, so typing "hello" is one undo step.
  • Macros: a MacroCommand holds a list of commands and undoes them in reverse order (a Composite of commands).
  • Memory limits: cap the history at N entries, or store snapshots as diffs instead of whole texts.
  • Autosave: the editor can publish "changed" events for a saver to subscribe to; see Observer.

Part 2: a chess engine core

Requirements

  • An 8 by 8 board with the standard starting position.
  • Six kinds of pieces that move differently: pawn, knight, bishop, rook, queen, king.
  • A game alternates between white and black. A move is accepted only if the piece belongs to the side to move and the target square is in the piece's list of moves.
  • Moves can be undone, including captures.
  • Count each side's material using the usual values (pawn 1, knight 3, bishop 3, rook 5, queen 9).
  • Out of scope, honestly: check and checkmate detection, castling, en passant, promotion, draws, a clock and any search or evaluation. A complete engine needs all of these. This core is the model they would be added to.

Strategy for movement

The tempting design is a class per piece with a big if on the kind inside the board. Instead, notice that movement comes in only a few shapes. Sliders (bishop, rook, queen) travel along directions until blocked. Steppers (knight, king) jump to fixed offsets. The pawn has its own odd rules. We model each shape as a movement strategy with one method, targets(board, row, col, piece). A bishop is a Slide with diagonal directions; a queen is a Slide with all eight; a king is a Step with the same eight. Adding a new fairy-chess piece is just a new combination of existing strategies. See Strategy and Bridge for the relation between the two ideas.

Composite for material

Each side is a tree: an army contains groups ("pawns", "officers"), and groups contain pieces. A caller who asks "what is the value of this?" should not care whether it is talking to one piece or to a whole army. A leaf (Piece) returns its own value, and a group returns the sum of its children. That is the Composite pattern, and it makes questions like "value of the white officers" trivial.

Command for moves

A MoveCommand records the piece, where it came from, where it went and what it captured, so undo can put everything back. Game is the invoker, exactly like the editor above.

Node.js Chess core: strategies, composite and undo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The test of the design is how little each piece needed. The board does not contain a single if (piece.kind === ...). The game rules (turns, validation, history) are separate from the movement rules, and the material count comes from a tree that did not exist in the board's own data.

Concurrency, failure paths and extensions

A chess game is turn-based, so a single Game object needs no locks as long as moves arrive one at a time. For an online server, serialize moves per game (one queue per game id) and reject moves whose expected turn number does not match. Illegal moves already throw and leave the board unchanged because validation comes before execute.

To grow toward a real engine you would add, in this order:

  1. King safety: a move is legal only if, after making it, the mover's king is not attacked. Generate the opponent's moves on a copy (or use execute and undo as above) and test.
  2. Special moves: castling, en passant and promotion, each as its own command subclass with a richer undo.
  3. Game states: a State for in-progress, check, checkmate and draw.
  4. Players: a Player interface with HumanPlayer and ComputerPlayer; the computer uses search over execute/undo, the reason undoable moves matter so much.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does ReplaceAllCommand store a snapshot instead of simply replacing the new text with the old text on undo?

    Replace-all has no clean inverse. A memento of the earlier state restores it exactly.
  2. 2. What happens to the redo stack when the user performs a brand-new action after an undo?

    Redoing commands recorded for a different history would produce a wrong document.
  3. 3. Why are the chess movement rules written as strategies instead of one board method with an if for each piece kind?

    Varying behavior gets its own object, which keeps the board closed to modification and open to new pieces.
  4. 4. What does the Composite pattern give the chess model?

    Leaf and group share the same interface, so callers never check which one they hold.
  5. 5. Why must validation happen before a command is executed and pushed on the history?

    Only actions that really happened belong on the undo stack. Otherwise undo reverses something that never occurred.

Summary

  • Turn user actions into command objects with execute and undo; the editor is the invoker, the document is the receiver.
  • Use a memento (an immutable snapshot) when an action has no clean inverse, such as replace-all.
  • Never record a command that failed; validate before pushing to the history, and clear the redo branch on a new action.
  • Chess movement comes in a few shapes. Strategy objects such as slide, step and pawn replace per-piece conditionals.
  • A composite tree of army, groups and pieces lets one value() call work at every level.
  • Moves as undoable commands make takebacks easy and are what a search-based engine builds on.
  • State clearly what is out of scope (check, castling, en passant, promotion) and where it would plug in.

Next lesson: Project: In-Memory File System.