Skip to content

Instantly share code, notes, and snippets.

@sword-jin
Created January 7, 2016 13:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sword-jin/82271a653dc7c5eb0982 to your computer and use it in GitHub Desktop.
Save sword-jin/82271a653dc7c5eb0982 to your computer and use it in GitHub Desktop.
JavaScript Command Pattern -- es5
function Calculator () {
this._currentValue = 0;
this.commands = [];
}
Calculator.prototype = {
execute: function(command) {
this._currentValue = command.execute(this._currentValue);
this.commands.push(command);
},
undo: function() {
var cmd = this.commands.pop();
this._currentValue = cmd.undo(this._currentValue);
},
getCurrentValue: function() {
return this._currentValue;
}
}
function Command (fn, undo, value) {
this.execute = fn;
this.undo = undo;
this.value = value;
}
function add (value) {
return value + this.value;
}
function AddCommand (value) {
Command.call(this, add, sub, value);
}
function sub (value) {
return value - this.value;
}
function SubCommand (value) {
Command.call(this, sub, add, value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment