javascript / expert
Snippet
Object-Oriented Command Stack Encapsulation using JS Private Fields and Proxies
Combining the object-oriented Command design pattern with strict class inheritance and encapsulated private arrays builds a deterministic undo/redo architecture suitable for state management in Svelte applications.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Command {execute() { throw new Error('Abstract method'); }undo() { throw new Error('Abstract method'); }}export class TransactionManager {#undoStack = [];#redoStack = [];execute(command) {if (!(command instanceof Command)) throw new TypeError('Invalid command instance');command.execute();this.#undoStack.push(command);this.#redoStack.length = 0;}undo() {const cmd = this.#undoStack.pop();if (cmd) {cmd.undo();this.#redoStack.push(cmd);}}}
svelte
Breakdown
1
class Command {
Declares an abstract interface class for command objects using object polymorphism.
2
#undoStack = [];
Encapsulates execution history inside private class fields to prevent untracked mutation.
3
if (!(command instanceof Command)) throw new TypeError('Invalid command instance');
Enforces dynamic type safety by verifying structural subclass hierarchy via instanceof.
4
this.#undoStack.push(command);
Records state mutations polymorphically to allow step-by-step state rollbacks.