Design Patterns

Published by Brayan K

Master proven solutions to common programming problems with battle-tested design patterns.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Start with a changing requirement, then choose a boundary

Suppose a small text editor needs append, uppercase and undo. The useful design question is not how many patterns can fit into it. It is which part should know how to change text, and which part should remember previous states. A command represents an action behind a consistent interface; the editor can run different actions without containing their individual algorithms.

const append = suffix => ({
  execute: text => text + suffix
});
const uppercase = {
  execute: text => text.toUpperCase()
};
function createEditor(initial) {
  let text = initial;
  const history = [];
  return {
    run(command) {
      const next = command.execute(text); // Compute before committing history.
      history.push(text); // Save the exact previous string, not an inverse guess.
      text = next;
    },
    undo() {
      if (history.length === 0) return false;
      text = history.pop();
      return true;
    },
    read: () => text
  };
}
const editor = createEditor("Hello");
editor.run(append(" Ada"));
editor.run(uppercase);
console.log(editor.read());
console.log(editor.undo(), editor.read());
console.log(editor.undo(), editor.read());
console.log(editor.undo(), editor.read());

// ✅ Expected output:
// HELLO ADA
// true Hello Ada
// true Hello
// false Hello

The commands above are plain objects with execute(text), not subclasses. The editor stores previous strings separately. This example combines an action interface with snapshots; calling the interface Command does not automatically provide reversal. The initial example assumes pure synchronous commands that return strings. We will make that contract explicit and test failures.

A pattern is a design vocabulary, not a JavaScript keyword or a promise of faster code. If there is only one fixed transformation, a plain function can be enough:

function greeting(name) {
  return "Hello " + name.trim();
}
console.log(greeting(" Ada "));

// ✅ Expected output:
// Hello Ada

An interface needs behavior as well as a matching method name

Our command contract is execute(currentText): it returns a new string, does not mutate external state and finishes synchronously. An object with a method named execute can still violate that contract. Check a public boundary before committing the new editor state.

function apply(command, text) {
  if (command === null || typeof command !== "object" ||
      typeof command.execute !== "function") {
    throw new TypeError("Command must provide execute(text)");
  }
  const next = command.execute(text);
  if (typeof next !== "string") throw new TypeError("Command must return a string");
  return next;
}
console.log(apply({}, "Hello"));

// ✅ Expected error:
// TypeError: Command must provide execute(text)
function apply(command, text) {
  const next = command.execute(text);
  if (typeof next !== "string") throw new TypeError("Command must return a string");
  return next;
}
const command = { async execute(text) { return text + "!"; } };
console.log(apply(command, "Hello"));

// ✅ Expected error:
// TypeError: Command must return a string

The async method returns a promise, even though its body looks simple. A genuinely asynchronous editor would need a different contract for pending work, failures and ordering. Async/Await owns that execution model; adding await to one line is not a complete concurrent editing policy.

function surround(text, before, after) {
  return before + text + after;
}
const quoteCommand = {
  execute(text) { return surround(text, "[", "]"); }
};
console.log(quoteCommand.execute("Notes"));

// ✅ Expected output:
// [Notes]

The adapter translates the interface the editor expects into the interface the existing function provides. It does not change that function’s semantics. Functions owns parameters and returns, while Closures and Scope owns how command factories can retain their arguments.

Undo requires enough information to restore the actual previous state

Not every operation has a unique inverse. Lowercasing uppercase text cannot recover the original capitalization. Saving the previous string preserves information that the forward operation discards.

const original = "Ada McKay";
const changed = original.toUpperCase();
const guessedUndo = changed.toLowerCase();
console.log(original);
console.log(changed);
console.log(guessedUndo);
console.log(guessedUndo === original);

// ✅ Expected output:
// Ada McKay
// ADA MCKAY
// ada mckay
// false

Even seemingly reversible operations have boundary cases. An append inverse based on slice(0, -suffix.length) fails for an empty suffix because negative zero is still zero:

const original = "Notes";
const suffix = "";
const changed = original + suffix;
console.log(changed.slice(0, -suffix.length));
console.log(changed.slice(0, -suffix.length) === original);
console.log("snapshot", original);

// ✅ Expected output:
//
// false
// snapshot Notes

Snapshots trade extra retained data for a simpler reversal contract. This lesson stores immutable strings. A snapshot that merely references a mutable object would change when that object changes; a shallow copy may still share nested objects. Spread & Rest Operators owns those reference boundaries.

const record = { text: "Before" };
const history = [record];
record.text = "After";
console.log(history[0].text);
console.log(history[0] === record);

// ✅ Expected output:
// After
// true

Only successful changes should enter history

Calculate and validate the next state before pushing the current state into history. If a transformation throws, the editor should retain its current text and the previous undo history. Error handling that returns a fake successful value would break that guarantee.

function createEditor(initial) {
  let text = initial;
  const history = [];
  return {
    run(command) {
      const next = command.execute(text);
      if (typeof next !== "string") throw new TypeError("Expected a string");
      history.push(text);
      text = next;
    },
    read: () => text,
    depth: () => history.length
  };
}
const editor = createEditor("A");
editor.run({ execute: text => text + "B" });
try {
  editor.run({ execute() { throw new Error("Transform failed"); } });
} catch (error) {
  console.log(error.message);
}
console.log(editor.read(), editor.depth());

// ✅ Expected output:
// Transform failed
// AB 1

This is a local in-memory commit boundary, not a transaction across files, databases or remote services. A command that sends a request and then throws cannot have that request undone by resetting a string. Error Handling owns propagating unexpected failures; broader recovery needs an application-specific design.

History is a stack, and a new branch invalidates the old redo path

let text = "A";
const history = [];
for (const suffix of ["B", "C"]) {
  history.push(text);
  text += suffix;
}
console.log(text);
text = history.pop();
console.log(text);
text = history.pop();
console.log(text);

// ✅ Expected output:
// ABC
// AB
// A

Using shift instead of pop would restore the oldest saved state first, skipping the most recent step. Redo needs a separate stack of states that were undone. After a new change, the previously undone future no longer belongs to the current branch.

let text = "A";
const past = [];
const future = [];
function change(next) {
  past.push(text);
  text = next;
  future.length = 0;
}
function undo() {
  if (past.length === 0) return false;
  future.push(text);
  text = past.pop();
  return true;
}
change("AB");
change("ABC");
undo();
console.log(text, future.join(","));
change("AB!");
console.log(text, future.length);

// ✅ Expected output:
// AB ABC
// AB! 0

A history must also have a retention policy. Keeping every old string forever can make a long editing session retain growing amounts of data. A small bounded history deliberately gives up older undo steps. The bound is a product decision; it is not a garbage-collection guarantee.

const limit = 2;
let text = "";
const history = [];
for (const suffix of ["A", "B", "C", "D"]) {
  history.push(text);
  if (history.length > limit) history.shift();
  text += suffix;
}
console.log(text);
console.log(JSON.stringify(history));
console.log(history.length);

// ✅ Expected output:
// ABCD
// ["AB","ABC"]
// 2

Choose other patterns by the change they isolate

Creation rules, interchangeable algorithms and subscriber lifetimes are different problems. JavaScript Design Patterns (Factory, Singleton, Strategy, etc.) owns Factory, Singleton, Strategy, Observer, Decorator and Facade implementations. Here, command objects isolate text actions and the editor owns history; adding those other patterns would need a separate requirement.

Before introducing another abstraction, describe the concrete change it should make easier, the interface each side must honor and how a failure affects state. Shared instances need an owner and a lifetime; a singleton label does not make global mutable state harmless. Classes, closures and plain functions are implementation choices, not scores for architectural maturity.

Guided exercise: commit only a valid transformed string

Complete the candidate calculation, type check and history entry. The bad command must leave text and history unchanged.

let text = "A";
const history = [];
function run(command) {
  const next = command.___(text); // 👉 replace ___ with execute
  if (typeof next !== "___") throw new TypeError("Expected a string"); // 👉 replace ___ with string
  history.push(___); // 👉 replace ___ with text
  text = next;
}
run({ execute: value => value + "B" });
try { run({ execute: () => 7 }); }
catch (error) { console.log(error.message); }
console.log(text, history.join(","));

// ✅ Expected output:
// Expected a string
// AB A

Independent brief: a bounded editor with undo and redo

Write createEditor(initial, limit), accepting an initial string and an integer history limit from 1 through 20. Invalid arguments throw TypeError("Invalid editor options"). Return read(), status(), run(command), undo() and redo(). status returns a fresh object with past and future counts. Commands provide execute(text), return a string and have no external side effects. Invalid command shape or result throws a TypeError.

run computes and validates before changing anything. An identical string is a no-op: return false and preserve both history stacks. A changed string pushes the old state, drops the oldest past state if over the limit, clears future and returns true. undo and redo return false when unavailable; otherwise move the current string to the opposite stack, restore its most recent state and return true. Redo restores a saved string rather than executing a command again.

Check an empty undo, two edits, undo/redo, a new branch after undo, a failing command, a no-op that preserves redo, a wrong result type and eviction at the limit.

function createEditor(initial, limit) {
  if (typeof initial !== "string" || !Number.isInteger(limit) ||
      limit < 1 || limit > 20) throw new TypeError("Invalid editor options");
  let text = initial;
  const past = [];
  const future = [];
  return {
    read: () => text,
    status: () => ({ past: past.length, future: future.length }),
    run(command) {
      if (command === null || typeof command !== "object" ||
          typeof command.execute !== "function") {
        throw new TypeError("Command must provide execute(text)");
      }
      const next = command.execute(text);
      if (typeof next !== "string") throw new TypeError("Command must return a string");
      if (next === text) return false;
      past.push(text);
      if (past.length > limit) past.shift();
      text = next;
      future.length = 0;
      return true;
    },
    undo() {
      if (past.length === 0) return false;
      future.push(text);
      text = past.pop();
      return true;
    },
    redo() {
      if (future.length === 0) return false;
      past.push(text);
      text = future.pop();
      return true;
    }
  };
}
const append = suffix => ({ execute: text => text + suffix });
const editor = createEditor("A", 2);
console.log("empty", editor.undo());
editor.run(append("B"));
editor.run(append("C"));
console.log(editor.read(), JSON.stringify(editor.status()));
console.log("undo", editor.undo(), editor.read());
console.log("noop", editor.run({ execute: text => text }), JSON.stringify(editor.status()));
console.log("redo", editor.redo(), editor.read());
editor.undo();
editor.run(append("!"));
console.log("branch", editor.read(), editor.redo());
for (const command of [
  { execute() { throw new Error("Failed"); } },
  { execute: () => 7 },
  {}
]) {
  try { editor.run(command); } catch (error) { console.log(error.message); }
}
console.log("unchanged", editor.read(), JSON.stringify(editor.status()));
editor.run(append("?"));
editor.run(append("."));
console.log("bounded", JSON.stringify(editor.status()));
console.log(editor.undo(), editor.read());
console.log(editor.undo(), editor.read());
console.log(editor.undo(), editor.read());

// ✅ Expected output:
// empty false
// ABC {"past":2,"future":0}
// undo true AB
// noop false {"past":1,"future":1}
// redo true ABC
// branch AB! false
// Failed
// Command must return a string
// Command must provide execute(text)
// unchanged AB! {"past":2,"future":0}
// bounded {"past":2,"future":0}
// true AB!?
// true AB!
// false AB!

Undo and redo keep their combined retained history bounded by the configured limit; moving a state between stacks does not create a new action. These snapshots contain only local strings. Collaborative editing, asynchronous actions and durable undo logs require additional conflict and persistence rules.

Practice quiz

What does this complete program print? const command = { execute: text => text + "!" }; console.log(command.execute("Hi"));

  • Hi!
  • Hi
  • [object Object]
  • undefined

Answer: Hi!. A command can be a plain object that exposes the agreed operation.

What does this complete program print? const original = "McKay"; const guessedUndo = original.toUpperCase().toLowerCase(); console.log(guessedUndo === original);

  • true
  • false
  • undefined
  • TypeError

Answer: false. Uppercasing discarded the original capitalization; lowercasing cannot recover it.

What does this complete program print? let text = "A"; const history = []; history.push(text); text = "AB"; history.push(text); text = "ABC"; text = history.pop(); console.log(text);

  • A
  • ABC
  • AB
  • undefined

Answer: AB. The latest saved state is the first undo target.

What does this complete program print? const original = { text: "A" }; const snapshot = original; original.text = "B"; console.log(snapshot.text);

  • A
  • undefined
  • null
  • B

Answer: B. Saving a mutable reference does not preserve an independent historical value.

What does this complete program print? const future = ["ABC"]; let text = "AB"; text += "!"; future.length = 0; console.log(text, future.length);

  • AB! 0
  • AB! 1
  • ABC 0
  • AB 1

Answer: AB! 0. A new branch clears the old redo future.

What does this complete program print? let text = "A"; const history = []; try { const next = (() => { throw new Error("Failed"); })(); history.push(text); text = next; } catch {} console.log(text, history.length);

  • A 1
  • A 0
  • undefined 1
  • Failed 0

Answer: A 0. The transformation fails before state or history is committed.

What does this complete program print? const command = { async execute(text) { return text; } }; const next = command.execute("A"); console.log(typeof next === "string");

  • true
  • undefined
  • false
  • TypeError

Answer: false. An async method returns a promise, which violates this synchronous string-result contract.

What does this complete program print? const history = ["A", "AB"]; history.push("ABC"); if (history.length > 2) history.shift(); console.log(history.join(","));

  • A,AB
  • A,ABC
  • ABC,AB
  • AB,ABC

Answer: AB,ABC. Evicting the oldest state preserves the two most recent prior states.

Continue this course

Related lessons