Skip to content

Instantly share code, notes, and snippets.

@mlhaufe
Created June 21, 2018 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlhaufe/c42f6ea90658d0897938487c10eb8b8e to your computer and use it in GitHub Desktop.
Save mlhaufe/c42f6ea90658d0897938487c10eb8b8e to your computer and use it in GitHub Desktop.
TypeScript Command Pattern example for CLJS: <https://groups.google.com/forum/#!topic/comp.lang.javascript/N8jA1Blh9LY>
abstract class Command {
abstract execute(): void
}
abstract class UndoableCommand extends Command {
abstract undo(): void
}
class Direction {
static readonly UP = 0
static readonly RIGHT = 90
static readonly DOWN = 180
static readonly LEFT = 270
constructor(readonly angle: number) { }
// ... other methods ellided for clarity
opposite(): Direction {
return new Direction((this.angle + 180) % 360)
}
}
/**
* A class representing a Maze game
* where your moves can be undone
*/
class Maze {
// A "stack" of commands for history tracking
protected _commands: Command[]
//... methods for defining maze parts and rendering ellided for clarity
move(direction: Direction): void {
// ellided for clarity
}
protected _doCommand(command: Command) {
if (command) {
this._commands.push(command)
command.execute()
}
}
protected _undoCommand() {
if (this._commands.length) {
let top = this._commands[this._commands.length - 1]
if (top instanceof UndoableCommand) {
this._commands.pop()
top.undo()
}
}
}
}
// Define an undoable command
class MazeMove extends UndoableCommand {
constructor(
readonly maze: Maze,
readonly direction: Direction
) { super() }
execute(): void {
this.maze.move(this.direction)
}
undo(): void {
this.maze.move(this.direction.opposite())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment