Created
April 4, 2015 08:43
-
-
Save idiotWu/69e355ed3555559a393c to your computer and use it in GitHub Desktop.
redo/undo manager
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
var Manager = function (obj) { | |
this.target = obj; | |
this.history = []; | |
this.step = -1; | |
return this; | |
} | |
Manager.prototype.set = function (key, value) { | |
var me = this, | |
target = me.target; | |
me.step = me.history.length; | |
me.history.push({ | |
action: 'set', | |
key: key, | |
value: value, | |
previousValue: target[key] | |
}); | |
target[key] = value; | |
} | |
Manager.prototype.get = function (key) { | |
return this.target[key]; | |
} | |
Manager.prototype.del = function (key) { | |
var me = this, | |
target = me.target; | |
me.step = me.history.length; | |
me.history.push({ | |
action: 'del', | |
key: key, | |
value: undefined, | |
previousValue: target[key] | |
}); | |
delete target[key]; | |
} | |
Manager.prototype.undo = function () { | |
var me = this, | |
step = me.step, | |
target = me.target, | |
history = me.history; | |
if (step === -1) { | |
throw new Error('nothing to undo.'); | |
} | |
var operation = history[step]; | |
target[operation.key] = operation.previousValue; | |
me.step = --step; | |
} | |
Manager.prototype.redo = function () { | |
var me = this, | |
step = me.step, | |
target = me.target, | |
history = me.history; | |
if (step > history.length - 2) { | |
throw new Error('nothing to redo.'); | |
} | |
var operation = history[++step]; | |
if (operation.action === 'del') { | |
delete target[operation.key]; | |
} else { | |
target[operation.key] = operation.value; | |
} | |
me.step = step; | |
} | |
var undoRedo = function (obj) { | |
return new Manager(obj); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment