Skip to content

Instantly share code, notes, and snippets.

@soundyogi
Forked from sword-jin/command.js
Created January 18, 2017 01:39
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 soundyogi/35bee7d7f35456b4f038654b9b94ab9d to your computer and use it in GitHub Desktop.
Save soundyogi/35bee7d7f35456b4f038654b9b94ab9d 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