-
-
Save soundyogi/35bee7d7f35456b4f038654b9b94ab9d to your computer and use it in GitHub Desktop.
JavaScript Command Pattern -- es5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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